java中collectors.tomap的用法是什么

avatar
作者
筋斗云
阅读量:0

在Java中,Collectors.toMap()方法用于将流(Stream)元素收集到Map集合中。它接受两个参数,分别是keyMapper和valueMapper,用于指定如何生成Map的键和值。

语法:

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

参数说明:

  • T:流元素的类型
  • K:生成Map的键的类型
  • U:生成Map的值的类型
  • keyMapper:将流元素映射为键的函数
  • valueMapper:将流元素映射为值的函数

示例: 假设有一个Person类,包含name和age属性。现在有一个Person的List,我们想将List中的Person对象按照name作为键,age作为值,生成一个Map。

import java.util.List; import java.util.Map; import java.util.stream.Collectors;  public class Main {     public static void main(String[] args) {         List<Person> persons = List.of(                 new Person("Alice", 25),                 new Person("Bob", 30),                 new Person("Charlie", 35)         );          Map<String, Integer> map = persons.stream()                 .collect(Collectors.toMap(Person::getName, Person::getAge));         System.out.println(map);     } }  class Person {     private String name;     private int age;      public Person(String name, int age) {         this.name = name;         this.age = age;     }      public String getName() {         return name;     }      public int getAge() {         return age;     } } 

输出结果:

{Alice=25, Bob=30, Charlie=35} 

在上面的示例中,通过Collectors.toMap(Person::getName, Person::getAge),将List中的Person对象按照name作为键,age作为值,生成了一个Map。最后输出结果为{Alice=25, Bob=30, Charlie=35}

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!