首页 > 解决方案 > Java Collection 方法到 lambda 方法

问题描述

如何在没有任何循环或 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 ;

}

谢谢帮助:)

标签: javaarraylistmethodslambdacollections

解决方案


您应该使用以下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”,您只是将该逻辑委托给流框架。


推荐阅读