[英]How to do filter a list in Java8?
I'm used to C# and the lambda expressions, but i couldn't filter a java list based on certain criterias. 我已经习惯了C#和lambda表达式,但我无法根据某些标准过滤java列表。
Ex: 例如:
List<MyObject> list;
I need to get all the MyObject that have a isMyFlag() true. 我需要获得所有具有isMyFlag()的MyObject。
In C# is really easy using IEnumerable... Is there any similar to IEnumerable in Java? 在C#中使用IEnumerable真的很容易......在Java中有没有类似于IEnumerable的东西?
See the new Stream API in Java 8 请参阅Java 8中的新Stream API
You need to do a filter and then collect the results in a list using the Stream API: 您需要进行过滤,然后使用Stream API在列表中收集结果:
list.stream().filter(x -> x.isMyFlag()).collect(Collectors.toList());
With lambdas you could do the following: 使用lambdas,您可以执行以下操作:
List<MyObject> filteredList = list.stream().filter(myObj -> myObj.isMyFlag())
.collect(Collectors.toList());
To use the Stream API you need to call the stream() method. 要使用Stream API,您需要调用stream()方法。 This is perhaps a surprise coming from C# as you don't need to do this, but once you have got over that hurdle it should be much the same.
这可能是来自C#的一个惊喜,因为你不需要这样做,但是一旦你克服了这个障碍,它应该是相同的。
List<MyObject> list2 = list.stream()
.filter(m -> m.isMyFlag())
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.