在Java中,List是一种常用的集合类型。使用List的stream方法可以方便地对其中的元素进行各种操作。
下面是10个常用的List stream技巧及详细的使用示例:
List list = Arrays.asList("apple", "banana", "cherry");
list.stream().forEach(System.out::println);
//输出:
//apple
//banana
//cherry
List list = Arrays.asList(1, 2, 3, 4, 5);
List filteredList = list.stream()
.filter(i -> i % 2 == 0)
.collect(Collectors.toList());
System.out.println(filteredList);
//输出:[2, 4]
List list = Arrays.asList("apple", "banana", "cherry");
List lengths = list.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println(lengths);
//输出:[5, 6, 6]
List list = Arrays.asList(1, 2, 3, 4, 5);
int sum = list.stream().reduce(0, Integer::sum);
System.out.println(sum);
//输出:15
List list = Arrays.asList(5, 2, 1, 4, 3);
List sortedList = list.stream().sorted().collect(Collectors.toList());
System.out.println(sortedList);
//输出:[1, 2, 3, 4, 5]
List persons = Arrays.asList(
new Person("Alice", Gender.FEMALE),
new Person("Bob", Gender.MALE),
new Person("Charlie", Gender.MALE),
new Person("Diana", Gender.FEMALE),
new Person("Eva", Gender.FEMALE)
);
Map> groups = persons.stream()
.collect(Collectors.groupingBy(Person::getGender));
System.out.println(groups);
//输出:{FEMALE=[Alice, Diana, Eva], MALE=[Bob, Charlie]}
List list = Arrays.asList(1, 2, 3, 4, 5);
IntSummaryStatistics stats = list.stream().mapToInt(Integer::intValue).summaryStatistics();
System.out.println(stats);
//输出:IntSummaryStatistics{count=5, sum=15, min=1, average=3.000000, max=5}
List list = Arrays.asList(1, 2, 3, 2, 4, 3, 5);
List distinctList = list.stream().distinct().collect(Collectors.toList());
System.out.println(distinctList);
//输出:[1, 2, 3, 4, 5]
List list = Arrays.asList(1, 2, 3, 4, 5);
List limitedList = list.stream().limit(3).collect(Collectors.toList());
System.out.println(limitedList);
//输出:[1, 2, 3]
List list = Arrays.asList(1, 2, 3, 4, 5);
List skippedList = list.stream().skip(2).collect(Collectors.toList());
System.out.println(skippedList);
//输出:[3, 4, 5]
这些技巧可以帮助您更方便地处理List中的元素。当然,这只是stream API中的一部分,还有很多其他的技巧和用法,需要根据具体情况选择合适的方法。