ISHAN KUMAR GHOSH
ISHAN KUMAR GHOSH

Reputation: 266

What is the best way to combine 2 or more fields as a Key in a Map, using Java 8?

I have been facing multiple requirements where I need to convert a List to Map, and in some cases I need to combine 2 fields as keys for that map, Previously I used the below solution -

Map<String, Integer> employeePairs = employees.stream().collect(HashMap<String, Integer>::new,
            (m, c) -> m.put(c.getFirstName() + " " + c.getLastName(), c.employeeId),
            (m, u) -> {
            });

I found a new way but that use a different package apache Pair the code looks like this-

Map<Pair<String, String>, Integer> employeePairs = employees.stream().collect(HashMap<Pair<String, String>, Integer>::new,
            (m, c) -> m.put(Pair.of(c.getFirstName(), c.getLastName()), c.employeeId),
            (m, u) -> {
            });
    employeePairs.get(Pair.of("a1", "b1"));// way of accessing

Package -

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
</dependency>

Which is a better way? Or is there a more better way.

Upvotes: 0

Views: 2108

Answers (1)

Eklavya
Eklavya

Reputation: 18480

If you don't want to use an extra library for using only Pair class, you can use AbstractMap.SimpleEntry<K,V> for pairing two fields and to collect as map, it's better to use Collectors.toMap

Map<AbstractMap.SimpleEntry<String, String>, Integer> employeePairs =   
    employees.stream()
             .collect(Collectors.toMap(
                c -> new AbstractMap.SimpleEntry<>(c.getFirstName(), c.getLastName()),
                c -> c.employeeId
              ));

You can access data of AbstractMap.SimpleEntry using .getKey() and .getValue()

Upvotes: 1

Related Questions