java8 在原有foriterator循环下又提供了forEach的方法,不过与for循环不同的是forEach循环是建立在stream之上的,而且比for或iterator方便的是,可以循环Map对象

  • forEach对List的循环样例
@Test
public void listForeach(){
    List<String> lst = new ArrayList<String>(5){{
        add("A");
        add("B");
        add("H");
        add("O");
        add("M");
    }};
    lst.forEach(System.out::println);
    lst.forEach((item)-> System.out.println(item.concat("_")));
}
 
  • forEach对数组的循环 样例
@Test
public void arrForeach(){
    String[] strArr = new String[]{"A","B","C","D"};

    Arrays.stream(strArr).forEach(System.out::println);
}
 
  • forEach对int范围的循环 样例
@Test
public void numericForeach(){        
    IntStream.range(0,10).forEach(System.out::println);
}
 
  • forEach对Map的循环 样例:
@Test
public void mapForeach(){
    Map<String,Object> mps = new HashMap<String,Object>(5){{
        put("a",1);
        put("b",true);
        put("c",23.44F);
        put("d","hello");
        put("e",11L);
    }};
    mps.forEach((k,v)-> System.out.println(k.concat(":").concat(String.valueOf(v))));
    String str = "hello";
}

 

相关文章:

  • 2021-06-15
  • 2021-09-09
  • 2021-06-08
  • 2021-10-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-20
  • 2021-09-06
  • 2021-08-22
  • 2021-12-21
  • 2021-07-25
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案