Java8 stream 使用案例
以下是一些使用Java 8 Stream的示例:
- 过滤列表中的元素:
List<String> names = Arrays.asList("John", "Tom", "Jane", "Alice");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("J"))
.collect(Collectors.toList());
- 将列表元素进行映射:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream()
.map(number -> number * number)
.collect(Collectors.toList());
- 对列表进行排序:
List<String> names = Arrays.asList("John", "Tom", "Jane", "Alice");
List<String> sortedNames = names.stream()
.sorted()
.collect(Collectors.toList());
- 对列表进行分组:
List<Person> people = Arrays.asList(
new Person("John", 25),
new Person("Tom", 30),
new Person("Jane", 25),
new Person("Alice", 30)
);
Map<Integer, List<Person>> peopleByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
- 对列表进行统计:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
IntSummaryStatistics stats = numbers.stream()
.mapToInt(Integer::intValue)
.summaryStatistics();
int min = stats.getMin();
int max = stats.getMax();
int sum = stats.getSum();
double average = stats.getAverage();
long count = stats.getCount();
这些示例只是Stream API的一小部分,通过使用Stream API,您可以以更简洁和功能强大的方式处理集合数据
原文地址: https://www.cveoy.top/t/topic/iIdo 著作权归作者所有。请勿转载和采集!