java 如何使用Stream API计算每个Element的int字段的总和?

bpsygsoo  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(78)

我有下一节课:

public class Order {
    private List<Element> elements;
}

public class Element {
    private int size;
}

我需要使用Stream API创建一个方法,该方法返回顺序为keys的Map,以及顺序中每个元素大小的总和为values
例如对于

List<Order> orders = new ArrayList<>();

orders.add(Order.createOrder(List.of(element1, element2, element3)));
orders.add(Order.createOrder(List.of(element3)));

我们应该得到:

{order1 = 75, order2 = 30}

因为element1 = 20, element2 = 25, element3 = 30size
我试过这样的方法:

private static Map<Order, Integer> calculate(List<Order> orders) {
    return  orders.stream()
        .flatMap(o -> o.getElements().stream())
        .mapToInt(el -> el.getSize())
        .sum();
}

但这段代码计算的是所有元素的大小之和。我能在这里做什么?将感谢任何建议!

huwehgph

huwehgph1#

其逻辑是:对于每个订单,对元素求和:

class Element {
    private int value;
    public Element(int v) { value = v; }
    public int getValue() { return value; }
    public String toString() { return ""+value; }
}
class Order {
    public String name;
    public List<Element> elements;
    public Order(String n, List<Element> l) { name = n; elements = l; }
    public String toString() { return name; }
    public static Order createOrder(String n, List<Element> l) { return new Order(n,l); }
}

public class Main {
    public static void main(String []a) {
        List<Order> orders = new ArrayList<>();

        Element element1 = new Element(20);
        Element element2 = new Element(25);
        Element element3 = new Element(30);

        orders.add(Order.createOrder("order1", List.of(element1, element2, element3)));
        orders.add(Order.createOrder("order2", List.of(element3)));

        Map<Order,Integer> r = orders.stream()
                .collect(Collectors.toMap(o -> o, o -> o.elements.stream().mapToInt(Element::getValue).sum()));
        System.out.println(r);
    }
}

其给出:

{order1=75, order2=30}

如果你想要一个Map<String,Integer>,那么:

Map<String,Integer> r = orders.stream()
                .collect(Collectors.toMap(Object::toString, o -> o.elements.stream().mapToInt(Element::getValue).sum()));

相关问题