How to convert a loop that sometimes adds a converted value to a Java 8 / lambda thread?

How do you convert this to a Java 8 lambda expression?

List<String> inputStrings = new ArrayList<>(); // say, a list of inputStrings

ArrayList<SomeClass> outputResultStrings = new ArrayList();
for(String anInputString : inputStrings) {
    SomeClass someResult = doSomthing(anInputString);
    if (someResult != null) {
        outputResultStrings.add(someResult);
    }
}
+4
source share
3 answers

Your code essentially goes through the input lines, executes doSomthingfor each of them ( mapin Java terminology), ignores the results null( filterin Java terminology), and then produces a list of these results ( collectin Java terminology). And when you are all together:

List<SomeClass> outputResultStrings = 
    inputStrings.stream()
                .map(SomeClass::doSomething)
                .filter(x -> x != null)
                .collect(Collectors.toList());

EDIT:
As suggested by Tunaki, a non-null check can be cleared with Objects::nonNull:

List<SomeClass> outputResultStrings = 
    inputStrings.stream()
                .map(SomeClass::doSomething)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
+7
source
    List<String> inputStrings = new ArrayList<>(); // say, a list of inputStrings

    List<SomeClass> outputResultStrings = inputStrings.stream()
        .map(s -> doSomthing(s))
        .filter(e -> e != null)
        .collect(Collectors.toList());
+2
source
    ArrayList<SomeClass> list = inputStrings.stream()
    .map(SomeClass::doSomthing)
    .filter((someClazz)->{ 
              return someClazz!=null;
    })
    .collect(Collectors.toCollection(ArrayList::new));
+1

Source: https://habr.com/ru/post/1624554/


All Articles