private static final List<String> list = Lists.newArrayList("1","2","3","4","5");
private static final List<String> list2 = Lists.newArrayList("0","1","2","3","4");
@Test
public void stream(){
List<String> l = (List)list.stream().filter(it->list2.contains(it)).collect(Collectors.toList());
}
就这么简简单单的一行代码就能取出 list 和 list2 中的相同部分,再也不用写 for ,担心性能问题了。
拓展
@Test
public void stream(){
List<String> str = (List)list.stream().filter(it->
list2.stream().filter(it2 -> it.equals(it2)).count()!=0
).collect(Collectors.toList());
}
@Test
public void stream2(){
List<Integer> list = Lists.newArrayList(1,2,3,4,5);
long count = list.stream().filter(x -> {list.remove(0);return true;})
.count();
System.out.println(count);
}