0

Let

List<String> data = Arrays.asList("key1=value1", "key2=value2");

Is there a way in Java using the stream api to convert this to a HashMap?

i.e. {{key1 -> value1}, {key2 -> value2}}

HashMap<String, String> dataMap = data.stream().map(s -> s.split("=")).//some stuff here//.collect(//some stuff here//);
Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
theanos
  • 41
  • 5
  • 4
    See http://stackoverflow.com/questions/4138364/java-how-to-convert-list-to-map, or http://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v for example. – Alexis C. Jan 31 '17 at 18:45

1 Answers1

2
HashMap<String, String> map = data.stream()
                                  .map(s -> s.split("="))
                                  .collect(Collectors.toMap(s -> s[0], s -> s[1], (a, b) -> a, HashMap::new));
Daniel Puiu
  • 962
  • 6
  • 21
  • 29
  • I definitely tried that, but it doesn't compile. Array type expected; found: 'T' Error: java: incompatible types: inference variable R has incompatible bounds equality constraints: java.util.Map upper bounds: java.util.HashMap,java.lang.Object – theanos Jan 31 '17 at 19:05
  • I updated the answer. I added a cast to `HashMap` – Daniel Puiu Jan 31 '17 at 19:11
  • 3
    This is because `Collectors.toMap` returns a `Map`, not a `HashMap`. Even though I would've argued against using HashMap, you can still do that by calling one of the overloaded `Collectors.toMap` implementations, where it allows you to specify your custom map supplier. Would look along the lines of `Collectors.toMap(s -> s[0], s -> s[1], (a, b) -> a, HashMap::new)`. Note though that this will silently ignore duplicate map keys. – M. Prokhorov Jan 31 '17 at 19:14
  • 3
    @Daniel, please revert your update back, it is very dangerous to cast results of collector operations. While it is true that current map collector uses `HashMap`, it is not guaranteed and may be changed at any moment without prior notice, at which point you will "suddenly" receive massive load of `ClassCastException`s. – M. Prokhorov Jan 31 '17 at 19:15