Java8的lambda表达式遍历集合

Java8 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().filter(student -> student != null).forEach(student -> {
            if (student.getAge() < 20) System.out.println(student.toString());
        });

运行结果

Strudent{name=‘b’, age=11, sex=‘女’}
Strudent{name=‘a’, age=19, sex=‘男’}
Strudent{name=‘d’, age=15, sex=‘女’}

遍历list中某个元素

list.stream().filter(student -> student != null).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

以上都是lambda中最简单的一些应用;后续还会介绍一些其他的方法.

你可能感兴趣的:(java)