Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a map with Java stream API using a value outside the stream?

Tags:

I want to init a Map<String, BigDecimal> and want to always put the same BigDecimal value from outside of the stream.

BigDecimal samePrice; Set<String> set;  set.stream().collect(Collectors.toMap(Function.identity(), samePrice)); 

However Java complains as follows:

The method toMap(Function, Function) in the type Collectors is not applicable for the arguments (Function, BigDecimal)

Why can't I use the BigDecimal from outside? If I write:

set.stream().collect(Collectors.toMap(Function.identity(), new BigDecimal())); 

it would work, but that's of course not what I want.

like image 473
membersound Avatar asked Apr 01 '16 12:04

membersound


2 Answers

The second argument (like the first one) of toMap(keyMapper, valueMapper) is a function that takes the stream element and returns the value of the map.

In this case, you want to ignore it so you can have:

set.stream().collect(Collectors.toMap(Function.identity(), e -> samePrice)); 

Note that your second attempt wouldn't work for the same reason.

like image 112
Tunaki Avatar answered Sep 17 '22 09:09

Tunaki


Collectors#toMap expects two Functions

set.stream().collect(Collectors.toMap(Function.identity(), x -> samePrice)); 

You can find nearly the same example within the JavaDoc

 Map<Student, Double> studentToGPA      students.stream().collect(toMap(Functions.identity(),                                      student -> computeGPA(student))); 
like image 21
Yassin Hajaj Avatar answered Sep 20 '22 09:09

Yassin Hajaj