Java Lambda Parse a collection with conditional validation

I work with Java 8 Lambdas and have been successful in simple use cases. I came from a mixed background of Java and C # .NET, so I am familiar with lambda in code.

In my current use case, I am trying to return a list from a collection with named values. I did it successfully like this

values.stream().map(x -> x).collect(Collectors.toList()); 

Relatively simple and straightforward. I would like to do the same, but just add an element from the collection where the boolean flag on the element is set to true. I thought it would work like that

 values.stream().map(x -> { if(x.isActive())return ((Model)x);}).collect(Collectors.toList()) 

But the compiler continues to show this error: Type mismatch: cannot convert from List<Object> to List<Model> I believe that the compiler should be smart enough to know the type of output from the map function and really do it in my original simplified example. That is why I believe that this is not the best way to do this.

For any of the .NET stack, the equivalent in C # / LINQ will be

 values.Where(x => x.isActive()).ToList(); 

I know there are many other good ways to do this without lambdas, but I would like to know how I can achieve this in Java using Java Lambdas?

+5
source share
1 answer

I think filter is what you are looking for, not map

  values.stream().filter(x->x.isActive()).collect(Collectors.toList()); 
+7
source

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


All Articles