之前的博客讲了Stream的概念和一些基础的用法,现在我们再来看一下Stream的高级用法,老规矩咱们还是以例子来说明。
1.map用法:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<Integer> ages = names.stream()
.map(name -> name.length())
.collect(Collectors.toList());
System.out.println(ages); // 输出 [5, 3, 7]
这个例子使用了map方法将字符串列表映射为其长度的整数列表。
2.filter用法:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith("A"))
.collect(Collectors.toList());
System.out.println(filteredNames); // 输出 [Alice]
这个例子使用了filter方法来过滤出以"A"开头的字符串。
3.toMap用法:
List<Person> people = Arrays.asList(new Person("Alice", 20), new Person("Bob", 30), new Person("Charlie", 25));
Map<String, Integer> ageMap = people.stream()
.collect(Collectors.toMap(Person::getName, Person::getAge));
System.out.println(ageMap); // 输出 {Alice=20, Bob=30, Charlie=25}
这个例子使用了toMap方法将Person对象列表转换为一个映射,其中键是Person对象的名称,值是Person对象的年龄。如果键重复,则toMap方法会抛出IllegalStateException。
4.groupingBy用法:
List<Person> people = Arrays.asList(new Person("Alice", 20), new Person("Bob", 30), new Person("Charlie", 25));
Map<Integer, List<Person>> peopleByAge = people.stream()
.collect(Collectors.groupingBy(Person::getAge));
System.out.println(peopleByAge); // 输出 {20=[Alice], 30=[Bob], 25=[Charlie]}
这个例子使用了groupingBy方法将Person对象列表按年龄分组,并返回一个映射,其中键是年龄,值是具有该年龄的Person对象列表。