java Collectors.toMap 用法


1.pojo

public class Person {  
      
    private Integer id;  
    private String name;  
      
    public Person(Integer id, String name) {  
        this.id = id;  
        this.name = name;  
    }  
    public Integer getId() {  
        return id;  
    }  
    public void setId(Integer id) {  
        this.id = id;  
    }  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
      
      
  
}  

2. test

import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
import java.util.function.Function;  
import java.util.stream.Collectors;  
import java.util.stream.Stream;  
  
public class Test {  
    public static void main(String[] args) {  
  
        List<Person> list = new ArrayList();  
        list.add(new Person(1, "haha"));  
        list.add(new Person(2, "rere"));  
        list.add(new Person(3, "fefe"));  
  
  
          
        Map<Integer, Person> mapp = list.stream().collect(Collectors.toMap(Person::getId, Function.identity()));  
          
        System.out.println(mapp);  
          
        System.out.println(mapp.get(1).getName());  
          
        Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));  
  
        System.out.println(map);  
  
    }  
  
}  

3. output

得到的結果:

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

haha

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM