Java Stream API : what kind of map method collect(Collectors.toMap()) returns?

风格不统一 提交于 2021-02-08 17:35:27

问题


What kind of map "hm" is?

 Map<String,Person> hm;

    try (BufferedReader br = new BufferedReader(new FileReader("person.txt")) {
        hm = br.lines().map(s -> s.split(","))
               .collect(Collectors.toMap(a -> a[0] , a -> new Person(a[0],a[1],Integer.valueOf(a[2]),Integer.valueOf(a[3]))));

Does it depend on declaration?

Map<String,Person> hm = new HashMap<>();
Map<String,Person> hm = new TreeMap<>();

回答1:


No, initializing the variable referenced by hm is pointless, since the stream pipeline creates a new Map instance, which you then assign to hm.

The actual returned Map implementation is an implementation detail. Currently it returns a HashMap by default, but you can request a specific Map implementation by using a different variant of toMap().

You can see one implementation here:

public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                Function<? super T, ? extends U> valueMapper) {
    return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}

You can see that it passes a method reference to a HashMap constructor, which means a HashMap instance will be created. If you call the 4 argument toMap variant, you can control the type of Map implementation to be returned.

Similarly, toList() returns an ArrayList and toSet a HashSet (at least in Java 8), but that can change in future versions, since it's not part of the contract.



来源:https://stackoverflow.com/questions/56751993/java-stream-api-what-kind-of-map-method-collectcollectors-tomap-returns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!