Java 8 forEach简单例子

2019-10-10 11:11:56

参考地址 Java 8 forEach简单例子

1. forEach and Map

1.1 通常这样遍历一个Map

复制代码

复制代码

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("Item : " + entry.getKey() + " Count : " + entry.getValue());
}

复制代码

复制代码

 

1.2 在java8中你可以使用  foreach  + 拉姆达表达式遍历

复制代码

复制代码

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);

items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));

items.forEach((k,v)->{
    System.out.println("Item : " + k + " Count : " + v);
    if("E".equals(k)){
        System.out.println("Hello E");
    }
});

复制代码

复制代码

2. forEach and List

 2.1通常这样遍历一个List.

复制代码

复制代码

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

for(String item : items){
    System.out.println(item);
}

复制代码

复制代码

 2.2在java8中你可以使用   foreach + 拉姆达表达式 或者 method reference(方法引用)

复制代码

复制代码

List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");

//lambda
//Output : A,B,C,D,E
items.forEach(item->System.out.println(item));

//Output : C
items.forEach(item->{
    if("C".equals(item)){
        System.out.println(item);
    }
});

//method reference
//Output : A,B,C,D,E
items.forEach(System.out::println);

//Stream and filter
//Output : B
items.stream()
    .filter(s->s.contains("B"))
    .forEach(System.out::println);

复制代码

复制代码


  • 2018-02-23 14:22:50

    mysql的yearweek 和 weekofyear函数

    例如 2010-3-14 ,礼拜天 SELECT YEARWEEK('2010-3-14') 返回 11 SELECT YEARWEEK('2010-3-14',1) 返回 10 其中第二个参数是 mode ,具体指的意思如下: Mode First day of week Range Week 1 is the first week … 0 Sunday 0-53 with a Sunday in this year 1 Monday 0-53 with more than 3 days this year 2 Sunday 1-53 with a Sunday in this year 3 Monday 1-53 with more than 3 days this year 4 Sunday 0-53 with more than 3 days this year 5 Monday 0-53 with a Monday in this year 6 Sunday 1-53 with more than 3 days this year 7 Monday 1-53 with a Monday in this year 2.

  • 2018-02-23 17:20:44

    Mysql数据库If语句的使用

    MySQL的if既可以作为表达式用,也可在存储过程中作为流程控制语句使用,如下是做为表达式使用:

  • 2018-02-24 10:16:36

    Java工具类之Apache的Commons Lang和BeanUtils

    Apache Commons包估计是Java中使用最广发的工具包了,很多框架都依赖于这组工具包中的一部分,它提供了我们常用的一些编程需要,但是JDK没能提供的机能,最大化的减少重复代码的编写。