-2

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?

Pomacanthidae
  • 207
  • 1
  • 3
  • 8
  • See https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v [Java 8 List into Map] – skomisa Sep 01 '17 at 05:37

3 Answers3

4

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.

ruakh
  • 175,680
  • 26
  • 273
  • 307
1

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)
);
Irwan Hendra
  • 150
  • 10
-2

Java 8 Interable Foreach:

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())));
Bui Anh Tuan
  • 910
  • 6
  • 12