How to groupingBy into a Map and change the key type

依然范特西╮ 提交于 2021-02-08 23:40:26

问题


I have a code which is suppose to group a list of transaction objects into 2 categories;

public class Transaction {
    public String type;
    public Integer amount;
}

The following function divided the list into 2 categories by checking a condition. The output map of the stream operation is Map<Boolean, List<Transaction>>, but I would like to use a String as its key. So I converted them manually.

public static Map<String, List<Transaction>> partitionTransactionArray(List<Transaction> t1) {
    Map<Boolean, List<Transaction>> result = list.stream().collect(Collectors.groupingBy(e -> ((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000)));

    // I think this is not necessary
    Map<String, List<Transaction>> result1 = new HashMap<>();
    result1.put("APPROVED", result.get(true));
    result1.put("PENDING", result.get(false));

    return result1;
}

However, I think there must be a clever way that allows me to do this operation in a single stream operation.

Can some one help?

EDIT:

What if, instead of having a Map<String, List<Transactions>> returned, I want to have a Map<String, List<Integer>> returned where the List contains only the amount of the transaction.

How can I do it in a single stream operation?


回答1:


Replace

((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000)

by

((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000) ? "APPROVED" : "PENDING"

You should probably use an enum instead of magic string constants.




回答2:


You can use a downstream to partitioningBy instead of groupingBy using Collectors.mapping as:

Map<Boolean, List<Integer>> result = list.stream()
        .collect(Collectors.partitioningBy(e ->
                        ((e.type.equals("BUY") || e.type.equals("SELL")) && e.amount < 1000),
                Collectors.mapping(Transaction::getAmount, Collectors.toList())));


来源:https://stackoverflow.com/questions/55785686/how-to-groupingby-into-a-map-and-change-the-key-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!