lambda表达式是内联代码,可实现功能接口而无需创建匿名类。在Java 8中,forEach 语句可与lambda表达式一起使用,该表达式可减少通过Map 循环到单个语句,并迭代列表的元素。在Iterable 接口中定义的forEach()方法并接受lambda表达式作为参数。
import java.util.*; public class ListIterateLambdaTest { public static void main(String[] argv) { List<String> countryNames = new ArrayList<String>(); countryNames.add("India"); countryNames.add("England"); countryNames.add("Australia"); countryNames.add("Newzealand"); countryNames.add("South Africa"); // Iterating country names through forEach using Lambda Expression countryNames.forEach(name -> System.out.println(name)); } }
输出结果
India England Australia Newzealand South Africa
import java.util.*; public class MapIterateLambdaTest { public static void main(String[] args) { Map<String, Integer> ranks = new HashMap<String, Integer>(); ranks.put("India", 1); ranks.put("Australia", 2); ranks.put("England", 3); ranks.put("Newzealand", 4); ranks.put("South Africa", 5); // Iterating through forEach using Lambda Expression ranks.forEach((k,v) -> System.out.println("Team : " + k + ", Rank : " + v)); } }
输出结果
Team : Newzealand, Rank : 4 Team : England, Rank : 3 Team : South Africa, Rank : 5 Team : Australia, Rank : 2 Team : India, Rank : 1