How to use Collectors.toMap() in Java8
You can convert from a List to a Map by using Collectors.toMap().
List<Dto> dataList = Arrays.asList( new Dto(1, "sample1"), new Dto(2, "sample2"), new Dto(3, "sample3"), new Dto(4, "sample4") ); Map<Integer, String> map = dataList.stream().collect( Collectors.toMap( d -> d.getAge(), d -> d.getName(), (oldVal,newVal) -> newVal, LinkedHashMap::new));
The meanings of the arguments are as follows
| Argument | Meaning |
| :– | :– | first argument
| First Argument | Map’s key |
| Second Argument | Map’s value |
| Third Argument | First or second win in case of key overlap |
| Fourth argument | Class that implements the Map interface |
The third argument specifies which of the keys takes precedence in the case of duplicate keys. In the above case, the latter wins.
List<Dto> dataList = Arrays.asList( new Dto(1, "sample1"), new Dto(2, "sample2"), new Dto(3, "sample3"), new Dto(4, "sample4") );
If dataList is changed to the above, the contents of the map will look like this
{1=sample1, 2=sample2, 3=sample3, 4=sample4}
Next is the case of duplication.
List<Dto> dataList = Arrays.asList( new Dto(1, "sample1"), new Dto(2, "sample2"), new Dto(3, "sample3"), new Dto(3, "sample4") );
If dataList is changed to the above, the contents of the map will look like this
{1=sample1, 2=sample2, 3=sample4}
java.lang.IllegalStateException: Duplicate key
If the third argument is omitted, the default is a duplicate error.
final List<Dto> dataList = Arrays.asList(new Dto(1, "sample1"), new Dto(2, "sample2"), new Dto(3, "sample3"), new Dto(3, "sample4")); final Map<Integer, String> result = dataList.stream() .collect(Collectors.toMap(d -> d.getAge(), d -> d.getName()));
コメント