新特性学习:Java 8 Stream API应用实例
Java 8引入了Stream API,这使得处理集合和数据流变得更加简洁高效。下面是一些实际的Stream API应用例子:
过滤:
List<String> names = Arrays.asList("John", "Jane", "Doe");
List<String> femaleNames = names.stream()
.filter(n -> n.toLowerCase().contains("female"))))
.collect(Collectors.toList());
排序:
List<Integer> numbers = Arrays.asList(5, 1, 3, 4));
List<Integer> sortedNumbers = numbers.stream()
.sorted(Integer::compareTo)) // 使用自定义的比较器
.collect(Collectors.toList());
映射:
```java
MapwordCounts = new HashMap<>();
wordCounts.put(“Java”, 1);
wordCounts.put(“Stream”, 2);
wordCounts.put(“API”, 3);
List
.sorted(Map.Entry::comparingByValue)) // 使用自定义的比较器
.collect(Collectors.toList());
// 现在可以遍历排序后的结果:
for (Map.Entry
System.out.println(“Word: “ + entry.getKey() + “, Count: “ + entry.getValue());
}
```
这些例子展示了Stream API的强大功能,包括过滤、排序和映射等操作。
还没有评论,来说两句吧...