Stream 的 Collectors.toMap
in developCo-De with 0 comment

Stream 的 Collectors.toMap

in developCo-De with 0 comment

方法定义

public static <T, K, U>  
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,  
                                Function<? super T, ? extends U> valueMapper,  
                                BinaryOperator<U> mergeFunction)

示例

public class SteamExample {  
  
  public static void main(String[] args) {  
    Person person1 = new Person("1", "a");  
    Person person2 = new Person("2", "b");  
    Person person3 = new Person("2", "c");  
    List<Person> personList = new ArrayList<>();  
    personList.add(person1);  
    personList.add(person2);  
    personList.add(person3);  
    Map<String, String> map =  
        personList.stream()  
            .collect(Collectors.toMap(Person::getPid, 
                                      Person::getName, 
                                      (key1, key2) -> key1));  
    for (String key : map.keySet()) {  
      System.out.println(key + ": " + map.get(key));  
    }  
  }  
  
  @Data  
  @AllArgsConstructor  public static class Person {  
  
    private String pid;  
    private String name;  
  }  
}

参数说明

Comments are closed.