【问题标题】:Java Collection method to lambda methodJava Collection 方法到 lambda 方法
【发布时间】:2020-04-30 17:43:09
【问题描述】:

如何在没有任何循环或 if 的情况下将此方法更改为 lambda?

public Collection<String> test (Collection<String> strings) {
    ArrayList<String> arrayListOfStrings = new ArrayList();

    for(String str : strings) {
        if(str.length() >= 10) {
            String s = str.substring(str.length() / 2);
            if(s.charAt(0) >= 'a') {
                arrayListOfStrings.add(s.toUpperCase());
            }
        }
    }
    return arrayListOfStrings;
}

我已经尝试过这种方式,有人有其他或更好的解决方案吗?:

public Collection<String> test (Collection<String> strings) {

    ArrayList<String> arrayListOfStrings = new ArrayList<String>();
    Stream<String> myStream = strings.stream()
            .filter(str -> str.length() >= 10)
            .map(str -> str.substring(str.length()/2))
            .filter(str -> str.charAt(0) >= 'a');

    myStream.forEach(str -> arrayListOfStrings.add(str.toUpperCase()));

    return arrayListOfStrings ;

}

感谢帮助:)

【问题讨论】:

标签: java arraylist methods lambda collections


【解决方案1】:

您应该使用collect() 方法使用Collectors.toList()

public Collection<String> test(Collection<String> strings) {
    return strings.stream()
            .filter(str -> str.length() >= 10)
            .map(str -> str.substring(str.length() / 2))
            .filter(s -> s.charAt(0) >= 'a')
            .map(String::toUpperCase)
            .collect(Collectors.toList());
}

你的问题说:

没有任何循环或 if

但您应该知道filter() 使用if 语句,而collect() 使用循环来迭代流的元素,因此您没有消除“循环或if”,您只是将该逻辑委托给流框架。

【讨论】:

  • 非常感谢!我应该更好地描述它,任务是仅删除此方法的 if 和循环
【解决方案2】:

这里有一个解决方案。可能会慢一些,但这正是你想要的。

    public Collection<String> test2(Collection<String> strings, int minLength) {
        return strings.stream().filter(s -> s.length() >= minLength)
                .map(s -> s.substring(s.length() / 2))
                .filter(s -> s.charAt(0) >= 'a')
                .map(String::toUpperCase)
                .collect(Collectors.toList());
    }

【讨论】:

  • 您错过了toUpperCase() 部分。
  • 我的错误,不错的收获。谢谢。
  • 在执行s.charAt(0) &gt;= 'a' 之前调用toUpperCase() 会产生不同的结果,因为现在将排除所有字母。
猜你喜欢
  • 2015-10-29
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多