【问题标题】:Multiple Predicates to group collection to hashmap将集合分组到 hashmap 的多个谓词
【发布时间】:2018-12-05 03:42:55
【问题描述】:

我有一个对象列表如下 -

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

定义了用于识别每个状态事务的各个谓词。

预期输出将是一个哈希图,其中成功/失败/拒绝文本作为键,这些状态的总计数作为值

HashMap<String, Integer> ->
    {
        "Success": 1,
        "Failure":2,
        "Pending":2
    }

我无法在一次执行中继续执行此操作。现在,我分别计算。任何人都可以协助处理请求吗?

【问题讨论】:

    标签: java-8 java-stream predicate


    【解决方案1】:

    您可以先声明一个这样的枚举来表示您感兴趣的 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()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 2018-01-20
      • 1970-01-01
      • 2022-01-06
      • 2010-10-07
      • 2016-06-23
      • 1970-01-01
      相关资源
      最近更新 更多