简体   繁体   中英

Java 8 extracting/coverting List<Object> into Map<String, List<String>> using stream()

Trying to figure out how can i use the new Java 8 feature .stream() in my code effectively.

Here is my code in general

List<Item> list = db.query(sqlStatement, (rs, i) -> new Item(rs));

    Map<String, List<Item>> itemsByName = new HashMap<>();

    for (Item m : list) {
        if (!itemsByName.containsKey(m.getName())) {

            ArrayList<Item> items = new ArrayList<>();
                            items.add(m);

            itemsByName.put(m.getName(), items);
        } else {
            itemsByName.get(m.getName()).add(m);
        }
    }

By this (1)

List<Item> list = db.query(sqlStatement, (rs, i) -> new Item(rs));

I get the List of Items which looks like:

list(0): Name1:Value1

list(1): Name1:Value2

list(2): Name2:Value1

list(3): Name3:Value3

By this (2)

Map<String, List<Item>> itemsByName = new HashMap<>();

    for (Item m : list) {
        if (!itemsByName.containsKey(m.getName())) {

            ArrayList<Item> items = new ArrayList<>();
                            items.add(m);

            itemsByName.put(m.getName(), items);
        } else {
            itemsByName.get(m.getName()).add(m);
        }
    }

I want to get:

MapKey(Name1): List{Name1:Value1, Name1:Value2}

MapKey(Name2): List{Name2:Value1}

MapKey(Name3): List{Name3:Value3}

How to rewrite code (2) using the stream() to get the same result?

You appear to be implementing the standard "group by" primitive. This is supported out-of-the-box by the Streams API:

Map<String, List<Item>> itemsByName = 
    list.stream().collect(Collectors.groupingBy(Item::getName));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM