Java 8新特性:lambda表达式、流等实战案例
Java 8引入了许多新特性,包括 Lambda 表达式、Stream API 等。这里将为你提供一些实战案例:
Lambda 表达式:
a) 多个参数的匿名方法:List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println("Hello, " + name + "!")); // 输出每个名字的信息
b) 作为方法的返回值:
Map<String, Integer> counts = new HashMap<>();
counts.put("apple", 10);
counts.put("banana", 20);
System.out.println("Number of apples: " + counts.getIfPresent("apple")); // 输出苹果的数量
counts.replaceAll(p -> p.getKey().contains("a"))); // 替换所有以"a"开头的键值对
counts.forEach((key, value)) -> System.out.println(key + ": " + value)); // 打印所有键值对
Stream API:
a) 对集合进行操作,如排序、过滤等:List<Integer> numbers = Arrays.asList(3, 1, 4), Arrays.asList(2));
numbers.stream() // 创建一个Stream流
.flatMap(numbers2 -> numbers2.stream())) // 使用flatMap把每个子列表转换为Stream流
.sorted(Comparator.comparingInt(n -> n))) // 对所有元素进行排序(这里使用自定义比较器)
.collect(Collectors.toList())); // 把结果收集到List中
System.out.println(numbers); // 输出排序后的数字列表
通过以上实战案例,你可以更好地理解和掌握Java 8的新特性。
还没有评论,来说两句吧...