-1

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 :)

gtr
  • 1
  • 2
  • 1
    "without any loops, if's or iteration" -- you may not be fully clear on how streams work under the hood – Hovercraft Full Of Eels Jan 14 '20 at 01:14
  • 1
    What have you tried? Where are you stuck? Please make an **attempt**, instead of asking us to write your code for you. – Andreas Jan 14 '20 at 01:40
  • `new ArrayList()` is a *raw* generic. Do not use *raw* generics. [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/q/2770321/5221149) --- Use the diamond operator: `new ArrayList<>()`. [What is the point of the diamond operator (<>) in Java 7?](https://stackoverflow.com/q/4166966/5221149) – Andreas Jan 14 '20 at 01:41

2 Answers2

1

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());
    }
Jason
  • 5,154
  • 2
  • 12
  • 22
1

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.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • thanks a lot! I should have described it better, the task was to remove the if's and loops only for this method – gtr Jan 14 '20 at 01:57