如下案例分析了foreach循環和Java8 拉姆達表達式的區別code
public static void main(String[] args) { /* * foreach 和 list */ List<String> arrs = new ArrayList<>(); arrs.add("a"); arrs.add("b"); arrs.add("c"); arrs.add("d"); arrs.add("e"); arrs.add("f"); for (String str : arrs) { System.out.print(str+","); } System.out.println(); arrs.forEach(item->System.out.print(item+",")); System.out.println(); arrs.forEach(item->{ if("a".equals(item)){ System.out.println(item); } }); /* * foreach 和 map */ Map<String, Object> maps = new HashMap<>(); maps.put("key1", "a"); maps.put("key2", "b"); maps.put("key3", "c"); maps.put("key4", "d"); maps.put("key5", "e"); maps.put("key6", "f"); for (Map.Entry<String, Object> entry : maps.entrySet()) { System.out.println(entry); } maps.forEach((k,v)->System.out.println("item:"+k+",value:"+v)); maps.forEach((k,v)->{ if("a".equals(v)){ System.out.println(v); } }); }