-1

I have a List<Map.Entry<Long, String>>.

How do I convert this into a Map?

Currently I am doing the following, but it seems a bit verbose (and most importantly, it is not "fluent", i.e. a single expression, but requires a code block).

Map<Long, String> result = new HashMap<>();
entries.forEach(e -> result.put(e.getKey(), e.getValue()));
return result;

Java 10 is fine.

Thilo
  • 257,207
  • 101
  • 511
  • 656
  • 1
    I would go with Java 11 as 10 is eol. – Peter Lawrey Nov 11 '18 at 11:42
  • 1
    @PeterLawrey already? Oh my, they are moving fast... – Thilo Nov 11 '18 at 11:44
  • Java 11 is EOL in 4 months :P At that time many might shift to OpenJDK 11, instead of skipping to 12. e.g. https://adoptopenjdk.net/ – Peter Lawrey Nov 11 '18 at 12:20
  • Anyway, I meant this as in "use of Java 10 API are permissible" (in the hopes that we have something less boilerplatey than the Java 8 streams collectors now). Does Java 11 bring something new to the table here (such as Collection literals)? – Thilo Nov 11 '18 at 12:24
  • 1
    Not really imho, You can write `entries.forEach((var e) -> result.put(e.getKey(), e.getValue()));` note the `var e`, the real advantage is Long Term Support-ability. – Peter Lawrey Nov 11 '18 at 12:30

2 Answers2

2

If you know for sure there are no duplicate keys, this is sufficient:

Map<Long, String> result = entries.stream().collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));

If there may be duplicates, you'll have to add a merge function to handle them.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • Hmm. I made it a List of Map.Entry specifically to avoid having to specify again what the `::getKey` and `::getValue` should be, but I guess I'll have to go with that. – Thilo Nov 11 '18 at 11:38
  • 1
    I do like the Guava answer from the duplicate thread. https://stackoverflow.com/a/44904884/14955 And `java.util.Map.ofEntries` is close, too, but does not work with a list. – Thilo Nov 11 '18 at 11:40
  • What happens if I have duplicates but no merge function? – Thilo Nov 11 '18 at 12:27
  • 1
    @Thilo An exception is thrown. – Eran Nov 11 '18 at 12:28
2

Flatten it:

Map<Long, String> result = 
    entries.stream()
        .collect(toMap(e -> e.getKey(), e -> e.getValue(), (a, b) -> b);

The (a, b) -> b means that the last value for duplicate keys will be taken, which matches the semantics of your current approach.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243