I tried to follow Java 8 List into Map and try to change Set to Map in one list
Instead of looping (which works)
for (Type t : toSet()) {
map.put(Pair.of(t, Boolean.TRUE), this::methodAcceptingMap);
}
I tried with solutions as:
toSet().stream()
.collect(Collectors.toMap(Pair.of(Function.identity(), Boolean.TRUE),
this::methodAcceptingMap));
But got an error converting:
Type mismatch: cannot convert from Pair<Function<Object,Object>,Boolean>
to Function<? super T,? extends K>
My map
private Map<Pair<Type, Boolean>, BiConsumer<Pair<Type, Boolean>, Parameters>> map =
new HashMap<>();
Collectors.toMap
takes two functions, and neither of your arguments fits.
You should use:
Map<Pair<Type, Boolean>, BiConsumer<Pair<Type, Boolean>, Parameters>> map =
set.stream()
.collect(Collectors.toMap(el -> Pair.of(el, Boolean.TRUE),
el -> this::methodAcceptingMap));
The expression Pair.of(t, Boolean.TRUE)
is simply not of a Function
type. And this::methodAcceptingMap
could fit the signature of a BiConsumer
, but the method requires a Function. So el -> this::methodAcceptingMap
should be used as a function that takes a stream element and returns your BiConsumer
.
Note that the assignment context ( map =
) is important in this case. Without it, the target type of these lambda expressions will be missing and compilation will fail.
I don't quite get your example. In for
loop you're passing the same lambda for every value. I don't see sense in that. If you really want that, you need to pass obj -> (pair, param) -> this.methodAcceptingMap(pair, param)
:
toSet().stream().collect(Collectors.toMap(
obj -> Pair.of(obj, Boolean.TRUE),
obj -> (pair, param) -> this.methodAcceptingMap(pair, param)));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.