简体   繁体   中英

Java 8 get a list out of map based on condition

I have an Item class :

public class Item {
    String name;
    double price;
    // Getters & Setters
}

Now I have a map as Map<String, List<Item>> map; this map holds the name of the item and a corresponding list of items having the same name.

Now I want to find out all list of items matching a filter criterion.

Here is my filter List<String> filter basically it contains all list of names which I need to filter from map and get all the selected items as a final list.

List<Item> output = new ArrayList<>();
        filter.forEach(item -> {
            List<Item> list = map.get(item);
            if (list != null) {
                output .addAll(list);
            }
        });

Here I am using Lambda expression, now is there a way to simplify this code further using Lamda or method reference?

I'd stream the filter list, flat map it the to values on the list and then collect them as a oneliner:

List<Item> result = 
    filter.stream()
          .flatMap(f -> map.getOrDefault(f, Collections.emptyList).stream())
          .collect(Collectors.toList());

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