2017-10-27 3 views
-2

메서드 호출로 키와 값을 저장하는지도가 있습니다. 특정 메소드가 호출 된지도에서 값을 가져올 때. 기능 1은 다음과 같다자바 람다 식에서 다른 반환 형식을 얻는 식

Map<Character, IntUnaryOperator> commands = new HashMap<>(); 
commands.put('a', number -> funtion1(number)); 
commands.put('b', number -> funtion1(number)); 

char cmd = 'a'; 
IntUnaryOperator result= commands.get(cmd); 

System.out.println(" Return value is "+result.applyAsInt(101)); 

,

public static int funtion1(int number){ 
    System.out.println("hello"); 
    return number; 
} 

어떻게 내가 문자열 유형 또는 다른 유형을 반환하는 소스 코드를 수정할 수 있습니까?

+2

변경에 대한 reference method jusr에'IntUnaryOperator' 어떤 [다른 기능 인터페이스 유형 (https://docs.oracle.com에 하나 변경 /javase/8/docs/api/?java/util/function/package-summary.html)이 필요에 맞습니다. 아마도 UnaryOperator 입니다. – Holger

답변

2
  • IntUnaryOperator 그래서

(UnaryOperator<T>Function<T,T>입니다)

  • Function<T,R>T을 가지고 R을 발생합니다 (IntUnaryOperatorUnaryOperator<Integer>입니다) int을 가지고 T을 가지고 T을 발생합니다 int
  • UnaryOperator<T>됩니다당신은 Function<Integer,String> 필요

    public static void main(String[] args) throws ParseException { 
        Map<Character, Function<Integer, String>> commands = new HashMap<>(); 
        commands.put('a', Guitar::funtion1); // method reference 
        commands.put('b', number -> funtion1(number)); 
    
        char cmd = 'a'; 
        Function<Integer, String> result = commands.get(cmd);     // Function 
        System.out.println("Return value is " + result.apply(55));   // 55 bar 
        System.out.println("Return value is " + commands.get('b').apply(32)); // 32 bar 
    } 
    
    public static String funtion1(int text) { 
        System.out.println("hello"); 
        return text + " bar"; 
    } 
    
    • 나는 또한
  • +0

    감사합니다.하지만 정수를 전달하고 함수에서 문자열을 반환하고 싶습니다. 아이디어는 반환 유형의 유형과 다른 유형을 전달하는 것입니다. 여기에 문자열을 전달하고 문자열을 반환합니다. – AJN

    +1

    @AJN이'Function azro

    +0

    감사합니다. @azro. – AJN