【问题标题】:From if/else to Stream using Map.Entry [closed]将带有 If 语句的 For 循环转换为流
【发布时间】:2022-10-15 00:06:04
【问题描述】:

我想将以下带有if-statement 的for-loop 转换为Stream。

public Integer months() {
    
    String desiredObject = // initialize somehow
    Map<String, Integer> monthDays = new HashMap<>();
    
    monthDays.put("March", 31);
    monthDays.put("April", 30);
    
    Set<Map.Entry<String, Integer>> entrySet = monthDays.entrySet();
    
    for (Map.Entry<String, Integer> pair : entrySet) {
        if (desiredObject.equals(pair.getKey())) {
            return pair.getValue();
        }
    }
}

怎么做?

【问题讨论】:

    标签: java for-loop if-statement java-stream


    【解决方案1】:
    return entrySet.stream()
      .filter(pair -> desiredObject.equals(pair.getKey()))
      .map(Entry::getValue)
      .findAny().orElse(null);
    

    或者,或者只是

    return monthDays.get(desiredObject);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      相关资源
      最近更新 更多