Before Java 8 I would code it like this:
Map<String, K> resultMap = new HashMap<>();
for (str : stringsList) {
resultMap.put(str, new K(str, new X(), new Y());
}
Is there any way for me to do it Java 8 style instead?
Before Java 8 I would code it like this:
Map<String, K> resultMap = new HashMap<>();
for (str : stringsList) {
resultMap.put(str, new K(str, new X(), new Y());
}
Is there any way for me to do it Java 8 style instead?
In theory, you can write:
Map<String, K> resultMap =
stringsList.stream().collect(Collectors.toMap(
str -> /*key=*/ str,
str -> /*value=*/ new K(str, new X(), new Y())
));
(using java.util.stream.Collectors.toMap(Function, Function)).
In practice, I think your current code is probably clearer.
solving duplicate key collisions from ruakh's answer:
Map<String, K> resultMap = stringsList.stream()
.collect(Collectors.toMap(
str -> str,
str -> new K(str, new X(), new Y()),
(oldVal, newVal) -> newVal)
);
List<String> stringsList = Arrays.asList("123", "456", "789");
Map<String, K> resultMap = new HashMap<String, K>();
stringsList.forEach(item -> resultMap.put(item, new K(item, new X(), new Y())));