stream 里面的 Collectors.toMap 用法 ; list转map

https://blog.csdn.net/jiangpingjiangping/article/details/76474010


第一步:

[java]  view plain  copy
  1. package test;  
  2.   
  3. public class Person {  
  4.       
  5.     private Integer id;  
  6.     private String name;  
  7.       
  8.     public Person(Integer id, String name) {  
  9.         this.id = id;  
  10.         this.name = name;  
  11.     }  
  12.     public Integer getId() {  
  13.         return id;  
  14.     }  
  15.     public void setId(Integer id) {  
  16.         this.id = id;  
  17.     }  
  18.     public String getName() {  
  19.         return name;  
  20.     }  
  21.     public void setName(String name) {  
  22.         this.name = name;  
  23.     }  
  24.       
  25.       
  26.   
  27. }  


第二步:

[java]  view plain  copy
  1. package test;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6. import java.util.function.Function;  
  7. import java.util.stream.Collectors;  
  8. import java.util.stream.Stream;  
  9.   
  10. public class Test {  
  11.     public static void main(String[] args) {  
  12.   
  13.         List<Person> list = new ArrayList();  
  14.         list.add(new Person(1"haha"));  
  15.         list.add(new Person(2"rere"));  
  16.         list.add(new Person(3"fefe"));  
  17.   
  18.   
  19.           
  20.         Map<Integer, Person> mapp = list.stream().collect(Collectors.toMap(Person::getId, Function.identity()));  
  21.           
  22.         System.out.println(mapp);  
  23.           
  24.         System.out.println(mapp.get(1).getName());  
  25.           
  26.         Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));  
  27.   
  28.         System.out.println(map);  
  29.   
  30.     }  
  31.   
  32. }  

得到的结果:

{1=test.Person@4b9385, 2=test.Person@1311334, 3=test.Person@2a0b20}

haha

{1=haha, 2=rere, 3=fefe}


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值