【程序员进阶之路-Stream篇(三)】

之前的博客讲了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对象列表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值