Shimon Cohen
Shimon Cohen

Reputation: 105

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!

Upvotes: -1

Views: 880

Answers (2)

vincendep
vincendep

Reputation: 607

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());

Upvotes: 2

Mark
Mark

Reputation: 54

Unary-Operator functional interface returns some result but Consumer functional interface doesn't https://docs.oracle.com/javase/8/docs/api/java/util/function/Consumer.html https://docs.oracle.com/javase/8/docs/api/java/util/function/UnaryOperator.html

Upvotes: 2

Related Questions