Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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<>();
like image 925
harp1814 Avatar asked Mar 03 '23 19:03

harp1814


1 Answers

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.

like image 158
Eran Avatar answered May 08 '23 11:05

Eran