zoukankan      html  css  js  c++  java
  • java8 forEach Map List[转载]

    java8 forEach 在Map和List中的使用

    原始的使用

    Map<String, Integer> items = new HashMap<>();
    items.put("A", 10);
    items.put("B", 20);
    items.put("C", 30);
    items.put("D", 40);
    items.put("E", 50);
    items.put("F", 60);
    
    for (Map.Entry<String,Integer> entry : items.entrySet()){
        System.out.println("key:"+entry.getKey()+";value:"+entry.getValue());
    }
    //output
    A---10
    B---20
    C---30
    D---40
    E---50
    F---60

    forEach 使用方式

    items.forEach((k,v)->System.out.println("key : " + k + "; value : " + v));
    
    //output
    key : A value : 10
    key : B value : 20
    key : C value : 30
    key : D value : 40
    key : E value : 50
    key : F value : 60
    items.forEach((k,v)->{
        System.out.println("Item : " + k + " Count : " + v);
        if("E".equals(k)){
            System.out.println("Hello E");
        }
    });
    
    key : A; value : 10
    key : B; value : 20
    key : C; value : 30
    key : D; value : 40
    key : E; value : 50
    Hello E

    java8 List 原先的使用方式

    List<String> arrayList = new ArrayList<>();
    arrayList.add("A");
    arrayList.add("B");
    arrayList.add("C");
    arrayList.add("D");
    arrayList.add("E");
    
    for (String item:arrayList){
        System.out.println(item);
    }

    java8 forEach 使用方式

    arrayList.forEach(item->System.out.println(item));
    
    arrayList.forEach(System.out::println);
    
    arrayList.forEach(item->{
        if("C".equals(item)){
            System.out.println(item);
        }
    });
    
    arrayList.stream()
            .filter(s-> s.contains("B")||s.contains("C"))
            .forEach(System.out::println);
    
    arrayList.stream()
            .filter(s->s.contains("E"))
            .findFirst().ifPresent(s -> System.out.println(s));

    转自:http://blog.csdn.net/wtljiayou/article/details/53638284

  • 相关阅读:
    MySQL视图更新
    JavaScript经典作用域问题
    进程间通信的几种方式
    Vue(MVVM)、React(MVVM)、Angular(MVC)对比
    CDN(Content Delivery Network)技术原理概要
    单点登录实现原理(SSO)
    composer 实现自动加载原理
    PHP 反射的简单使用
    php7安装php-redis扩展
    Git 简单入门(二)
  • 原文地址:https://www.cnblogs.com/go-onxp/p/jdk8.html
Copyright © 2011-2022 走看看