遍历List
List<Strudent> list = new ArrayList<Strudent>() {{
add(new Strudent("b", 11, "女"));
add(new Strudent("a", 19, "男"));
add(new Strudent("d", 15, "女"));
add(new Strudent("c", 22, "男"));
}};
list.stream().forEach(student -> {
if (student.getAge() < 20)
System.out.println(student.toString());
});
上面一种是直接遍历结束之后过滤结果
还有一种是先过滤条件后遍历集合
List<Strudent> list = new ArrayList<Strudent>() {{
add(new Strudent("b", 11, "女"));
add(new Strudent("a", 19, "男"));
add(new Strudent("d", 15, "女"));
add(new Strudent("c", 22, "男"));
}};
list.stream().filter(student -> {
student.getAge() < 20
}).forEach(
System.out.println(student.toString());
});
运行结果
student{name=‘b’, age=11, sex=‘女’}
student{name=‘a’, age=19, sex=‘男’}
student{name=‘d’, age=15, sex=‘女’}
遍历list中某个元素
list.stream().filter(Objects :: nonNull).map(Strudent::getAge).filter(id->id!=null).forEach(id->{
System.out.println(id);
});
遍历map
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>() {{
put("a", "haha");
put("b", "hahaha");
put("d", "hahe");
put("c", "haheeee");
}};
map.forEach((k, v) -> {
System.out.print("key=" + k);
System.out.print("\t");
System.out.println("value=" + v);
});
}
输出结果
key=a value=haha
key=b value=hahaha
key=c value=haheeee
key=d value=hahe