简体   繁体   中英

How to get the member of inner object in a list of objects using Java 8

I have a class (Menu) with a list of objects(Recipe). Each object(Recipe) contains another object(Item) and quantity. I need to get the data as Map with Object. get id as key and quantity as value.

How to do this in Java 8?

class Menu{
  private List<Recipe> recipes;
}

class Recipe{
   private Item item;
   private Integer quantity;
}

class Item{
   private String itemId;
   private String itemName;
   private String description;
}

I need a map as <Item.itemId,Recipe.quantity> by streaming menu

Try this

Map<String, Integer> map = recipes.stream()
                .collect(Collectors.groupingBy(recipe -> recipe.getItem().getItemId(),
                        Collectors.summingInt(Recipe::getQuantity)));

An example:

Note: I only filled partial fields for the sake of demonstration

List<Recipe> recipes = new ArrayList<>();
Recipe r1 = new Recipe();
r1.setQuantity(2);
Item i1 = new Item();
i1.setItemId("1");
r1.setItem(i1);

Recipe r2 = new Recipe();
r2.setQuantity(5);
Item i2 = new Item();
i2.setItemId("1");
r2.setItem(i2);

Recipe r3 = new Recipe();
r3.setQuantity(3);
Item i3 = new Item();
i3.setItemId("2");
r3.setItem(i3);

recipes.addAll(Arrays.asList(r1, r2, r3));

Map<String, Integer> map = recipes.stream()
        .collect(Collectors.groupingBy(recipe -> recipe.getItem().getItemId(),
                Collectors.summingInt(Recipe::getQuantity)));

System.out.println(map);

Output:

{id2=3, id1=7}

Without lambdas, you can do it this way

Map<String, Integer> result = new HashMap<>();
for (Recipe recipe : recipes) {
    String key = recipe.getItem().getItemId();
    if (!result.containsKey(key)) {
        result.put(key, recipe.getQuantity());
    } else {
        result.put(key, recipe.getQuantity() + result.get(key));
    }
}

System.out.println(result);

You can do it as follows:

Map<String, Integer> map = menu.getRecipes().stream()
                .collect(Collectors.toMap(recipe -> recipe.getItem().getItemId(), recipe -> recipe.getQuantity()));

A sample complete code:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Item item1 = new Item("1", "Item1", "Item1 Description");
        Item item2 = new Item("2", "Item2", "Item2 Description");
        Item item3 = new Item("3", "Item3", "Item3 Description");

        Recipe recipe1 = new Recipe(item1, 3);
        Recipe recipe2 = new Recipe(item2, 5);
        Recipe recipe3 = new Recipe(item3, 7);

        Menu menu = new Menu();
        menu.getRecipes().add(recipe1);
        menu.getRecipes().add(recipe2);
        menu.getRecipes().add(recipe3);

        // System.out.println(menu.getRecipes());

        Map<String, Integer> map = menu.getRecipes().stream()
                .collect(Collectors.toMap(recipe -> recipe.getItem().getItemId(), recipe -> recipe.getQuantity()));

        map.forEach((k, v) -> System.out.println(k + " => " + v));
    }
}

class Menu {
    private List<Recipe> recipes;

    Menu() {
        recipes = new ArrayList<Recipe>();
    }

    public List<Recipe> getRecipes() {
        return recipes;
    }
}

class Recipe {
    private Item item;
    private Integer quantity;

    public Recipe(Item item, Integer quantity) {
        super();
        this.item = item;
        this.quantity = quantity;
    }

    public Item getItem() {
        return item;
    }

    public Integer getQuantity() {
        return quantity;
    }

    @Override
    public String toString() {
        return "Recipe [item=" + item + ", quantity=" + quantity + "]";
    }
}

class Item {
    private String itemId;
    private String itemName;
    private String description;

    public Item(String itemId, String itemName, String description) {
        super();
        this.itemId = itemId;
        this.itemName = itemName;
        this.description = description;
    }

    public String getItemId() {
        return itemId;
    }

    @Override
    public String toString() {
        return "Item [itemId=" + itemId + ", itemName=" + itemName + ", description=" + description + "]";
    }
}

Output:

1 => 3
2 => 5
3 => 7

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