Created
October 16, 2021 18:29
-
-
Save TheGreatJoules/e134dbdf7e1e458ad17994026aaf8beb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// You can use an initializer in an anonymous subclass to make the syntax a little bit shorter: | |
Map<String, String> myMap = new HashMap<String, String>() {{ | |
put("a", "b"); | |
put("c", "d"); | |
}}; | |
// In plain java 8 you also have the possibility of using Streams/Collectors to do the job. | |
Map<String, String> myMap = Stream.of( | |
new SimpleEntry<>("key1", "value1"), | |
new SimpleEntry<>("key2", "value2"), | |
new SimpleEntry<>("key3", "value3")) | |
.collect(toMap(SimpleEntry::getKey, SimpleEntry::getValue)); | |
// Using a Stream of a two-dimensional object and collect them into a map: | |
Map<String, Integer> map = Stream.of(new Object[][] { | |
{ "data1", 1 }, | |
{ "data2", 2 }, | |
}).collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment