javaconsumerfunctional-interfaceunary-operator

What is the difference between Unary-Operator functional-interface to Consumer functional-interface?


I was wondering what is the difference between Unary-Operator and Consumer functional interfaces?

Eventually, both of them get a function and apply it to a generic T.

Thank you in advance!


Solution

  • A Consumer is a method that take a parameter of a generic type T and has no return value (void).
    A UnaryOperator is a method that take a parameter of a generic type T and return a value of the same type (T).

    Example:

    //Traditionally
    public void convertToLowerCase(String str) {
      System.out.println(str.toLowerCase());
    }
    
    List<String> strings = Arrays.asList("YO", "SHIMON");
    for (String str : strings) {
      convertToLowerCase(str);
    }
    
    //With Consumer
    Consumer<String> consumer = str -> System.out.println(str.toLowerCase());
    List<String> strings = Arrays.asList("YO", "SHIMON");
    strings.forEach(consumer);
    
    **
    
    //Traditionally:
    public List<Integer> double(List<Integer> numbers) {
        List<Integer> doubleNumbers = new ArrayList<>();
        for (Integer number : numbers) {
            doubleNumbers.add(number * 2);
        }
        return doubleNumbers;
    }
    
    //With UnaryOperator:
    UnaryOperator<Integer> double = n -> n * 2;
    List<Integer> doubleNumbers = numbers.stream()
        .map(double)
        .collect(Collectors.toList());