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<>();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With