Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply Consumer with a map in Java?

I have created a Consumer which takes a string and makes it uppercase. I am trying to implement it along with a map to make all the strings in a list to uppercase. I understand that this can be done easily using String::toUpperCase but I am trying to do it with a Consumer and I am getting the following error

java: incompatible types: inferred type does not conform to upper bound(s)
    inferred: void
    upper bound(s): java.lang.Object

Here is my code

Consumer<String> upper = name -> name.toUpperCase();
names.stream().map(name -> upper.accept(name)).collect(Collectors.joining(" "))

I want to know if this is the correct way to use Consumer interface and also what would be a typical scenario where using Consumer would be helpful?

like image 913
Varun Upadhyay Avatar asked Sep 13 '26 08:09

Varun Upadhyay


1 Answers

Consumer#accept returns nothing (void), so it will not compile, as Stream#map accepts a Function<? super T, ? extends R>. Instead of a Consumer, you can use a UnaryOperator<String> (which is a special Function<T, T>):

UnaryOperator<String> upper = String::toUpperCase;

names.stream()
     .map(upper)
     .collect(Collectors.joining(" "));

You also don't even need to store it in a local variable, as it can be inlined:

names.stream()
     .map(String::toUpperCase)
     .collect(Collectors.joining(" "));
like image 80
Jacob G. Avatar answered Sep 15 '26 22:09

Jacob G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!