问题
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