本文介绍了Java Stream API:什么样的地图方法collect(Collectors.toMap())返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"hm"是什么样的地图?

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]))));

这取决于声明吗?

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

推荐答案

不,初始化hm引用的变量是没有意义的,因为流管道会创建一个新的Map实例,然后将其分配给hm

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

实际返回的Map实现是实现细节.当前,它默认情况下返回HashMap,但是您可以使用toMap()的其他变体来请求特定的Map实现.

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);
}

您可以看到它将方法引用传递给HashMap构造函数,这意味着将创建一个HashMap实例.如果调用4参数toMap变体,则可以控制要返回的Map实现的类型.

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.

类似地,toList()返回一个ArrayListtoSet一个HashSet(至少在Java 8中),但是由于它不是合同的一部分,因此在将来的版本中可能会更改.

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.

这篇关于Java Stream API:什么样的地图方法collect(Collectors.toMap())返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:22