lambda遍歷集合

遍歷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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章