Java 8 将集合分组到hashmap的多个谓词
我的物品清单如下:Java 8 将集合分组到hashmap的多个谓词,java-8,java-stream,predicate,Java 8,Java Stream,Predicate,我的物品清单如下: List<Transaction> 列表 事务对象看起来像什么 Transaction { String Status; } Status <A,B,C,D,E,F,G...> If Status in (A,B,C)->Success If Status in (D,E,F)->Failure If Status in (G,H...)->Pending 事务{ 字符串状态; } 地位 如果状态为(A、B、C)-
List<Transaction>
列表
事务对象看起来像什么
Transaction {
String Status;
}
Status <A,B,C,D,E,F,G...>
If Status in (A,B,C)->Success
If Status in (D,E,F)->Failure
If Status in (G,H...)->Pending
事务{
字符串状态;
}
地位
如果状态为(A、B、C)->成功
如果状态为(D、E、F)->故障
如果状态为(G,H…)->挂起
定义了用于标识每个状态事务的单个谓词
预期的输出将是一个hashmap,其中Success/Failure/Rejected文本作为键,这些状态的集合计数作为值
HashMap<String, Integer> ->
{
"Success": 1,
"Failure":2,
"Pending":2
}
HashMap->
{
"成功":一,,
"失败":二,,
“待定”:2
}
我无法在一次执行中继续执行该操作。现在,我要分别统计。任何人都可以协助请求吗?您可以先声明这样的枚举,以表示您感兴趣的3个状态
public enum TxStatus {
Success, Failure, Pending;
}
然后在Transaction
中编写一个方法,将String
文本值转换为您期望的真实状态值。这里有一个这样的实现
public class Transaction {
private final String status;
private Pattern SUCCESS_PATTERN = Pattern.compile("[ABC]");
private Pattern FAILURE_PATTERN = Pattern.compile("[DEF]");
private Pattern PENDING_PATTERN = Pattern.compile("[GHI]");
public Transaction(String status) {
super();
this.status = status;
}
public String getStatus() {
return status;
}
public TxStatus interpretStatus() {
if (SUCCESS_PATTERN.matcher(status).matches()) {
return TxStatus.Success;
}
if (FAILURE_PATTERN.matcher(status).matches()) {
return TxStatus.Failure;
}
if (PENDING_PATTERN.matcher(status).matches()) {
return TxStatus.Pending;
}
throw new IllegalArgumentException("Invalid status value.");
}
}
最后,您的客户端代码应该如下所示
Map<String, Long> txStatusToCountMap = txs.stream()
.collect(Collectors.groupingBy(tx -> tx.interpretStatus().toString(),
Collectors.counting()));
Map txStatusToCountMap=txs.stream()
.collect(收集器.groupingBy(tx->tx.interpretatus().toString(),
收集器。计数();
您可以先声明这样的枚举,以表示您感兴趣的3个状态
public enum TxStatus {
Success, Failure, Pending;
}
然后在Transaction
中编写一个方法,将String
文本值转换为您期望的真实状态值。这里有一个这样的实现
public class Transaction {
private final String status;
private Pattern SUCCESS_PATTERN = Pattern.compile("[ABC]");
private Pattern FAILURE_PATTERN = Pattern.compile("[DEF]");
private Pattern PENDING_PATTERN = Pattern.compile("[GHI]");
public Transaction(String status) {
super();
this.status = status;
}
public String getStatus() {
return status;
}
public TxStatus interpretStatus() {
if (SUCCESS_PATTERN.matcher(status).matches()) {
return TxStatus.Success;
}
if (FAILURE_PATTERN.matcher(status).matches()) {
return TxStatus.Failure;
}
if (PENDING_PATTERN.matcher(status).matches()) {
return TxStatus.Pending;
}
throw new IllegalArgumentException("Invalid status value.");
}
}
最后,您的客户端代码应该如下所示
Map<String, Long> txStatusToCountMap = txs.stream()
.collect(Collectors.groupingBy(tx -> tx.interpretStatus().toString(),
Collectors.counting()));
Map txStatusToCountMap=txs.stream()
.collect(收集器.groupingBy(tx->tx.interpretatus().toString(),
收集器。计数();