简体   繁体   中英

Java Collection method to lambda method

how can i change this method to lambda without any loops or if's?

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;
}

i've tried it this way, someones got another or better solution?:

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 ;

}

thx for help :)

here is a solution. likely slower but this is what you wanted.

    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());
    }

You should use the collect() method using 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());
}

Your question said:

without any loops or if's

but you should be aware that filter() uses an if statement, and collect() uses a loop to iterate the elements of the stream, so you haven't eliminated "loops or if's", you've just delegated that logic to the stream framework.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM