gsdev
gsdev

Reputation: 259

Grouping a List of Items using java 8 Streams and populating resulting Map with FIRST Item rather than List

I have an item defined by the following class:

public class Item {
    private int id;
    private float price;
}

I've been given a list of items and I need to group them by id. Once grouped, I know the List will only ever contain a single value for each id, so I want the resulting Map to be defined as follows:

Map<Integer, Item>

rather than:

Map<Integer, List<Item>>

The benefit of this, is that my calling code will not need to perform extra dereferencing:

mapName.get(id).get(0)

The following code will group the items by id and create a Map containing a list:

Map<Integer, List<Item>> itemsMap = itemList.stream()
        .collect(Collectors.groupingBy(Item::getId));

Is there a way in Java 8 to achieve my desired result?

Upvotes: 6

Views: 2809

Answers (3)

Naman
Naman

Reputation: 31868

One way to do around such conversions using IDE's such as intelliJ is:

List<Item> itemList = ...
Map<Integer, Item> itemMap = new HashMap<>();
for (Item item : itemList) {
    itemMap.put(item.getId(), item);
}

and then convert/replace the statement as:

Map<Integer, Item> itemMap =
            itemList.stream().collect(Collectors.toMap(Item::getId, item -> item, (a, b) -> b)); 

which is same as John's answer.

Upvotes: 1

Bender
Bender

Reputation: 647

You can use: Map<Integer, Item> itemsMap = items.stream().collect(Collectors.toMap(Item::getId, Function.<Item>identity()));

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361565

itemList.stream()
    .collect(Collectors.toMap(item -> item.id, item -> item));

Upvotes: 2

Related Questions