问题
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