Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Lambda's Parse down a Collection with a Conditional Check

I'm working with Java 8 Lambdas, and have had success with simple use cases. I come from a mixed background of Java and C# .NET so I'm familiar with lambda's in code.

In my current use case I'm trying to return a List from a Collection named values. I've done this successfully like this

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

Relatively simple and straightforward. I'd like to do the same thing, but only add item's from the Collection where a boolean flag on the item is set to true. I thought that would work like this

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

But the compiler keeps showing this error : Type mismatch: cannot convert from List<Object> to List<Model> I believe the compiler should be smart enough to know the output type from the map function and indeed does on my original simplified example. That's why I believe this is not the best way to do this.

For anyone from the .NET stack, the equivalent in C#/LINQ would be

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

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

like image 459
Mabdullah Avatar asked Oct 30 '14 16:10

Mabdullah


1 Answers

I think that filter is what you looking for and not a map

 values.stream().filter(x->x.isActive()).collect(Collectors.toList());      
like image 119
Sleiman Jneidi Avatar answered Oct 09 '22 17:10

Sleiman Jneidi