0

Есть класс:

String branchName;
Integer corporateContractCount;
Integer executorContractCount;

Есть список из объектов этого класса List.

Как можно с помощью stream api посчитать в сумму элементов corporateContractCount, сумму элементов executorContractCount, и сгруппировать все по branchName?

0

1 ответ 1

1

С помощью метода: Collectors.toMap(,,,) можно собрать элементы листа в карту Map<String, Integer> и сложить нужные поля:

public class Test {
    public static void main(String[] args) {
        List<SomeClass> list = new ArrayList<>();
        list.add(new SomeClass("Someone", 3, 2));
        list.add(new SomeClass("AnotherOne", 4, 6));
        list.add(new SomeClass("Someone", 1, 4));

        Map<String, Integer> someones = list.stream()
                // собираем из листа карту
                .collect(Collectors.toMap(
                        // ключ - строка
                        e -> e.name,
                        // значение - число,
                        // суммируем два поля
                        e -> e.field1 + e.field2,
                        // суммируем значения
                        // повторяющихся элементов
                        Integer::sum,
                        // имплементация карты
                        // с сортировкой элементов
                        // в порядке добавления
                        LinkedHashMap::new));

        System.out.println(someones); // {Someone=10, AnotherOne=10}
    }
}
public class SomeClass {
    String name;
    int field1;
    int field2;

    public SomeClass(String name, int field1, int field2) {
        this.name = name;
        this.field1 = field1;
        this.field2 = field2;
    }
}

См. Группировка нескольких полей в Stream API

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.