使用javaCollectors.toMap()方法

Collectors.toMap()是Java 8中的一个流操作,它可以将一个流转换为一个Map对象。

定义一个测试类

package com.dreams.LamJava;

/**
* @author PoemsAndDreams
* @date 2024-01-21 21:33
* @description //TODO 测试类
*/
public 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;
    }


    @Override
    public String toString() {
        return "Person{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }

}

Collectors.toMap()方法将一个流转换为一个Map,其中key是Person对象的name属性,value是Person对象本身

package com.dreams.LamJava;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* @author PoemsAndDreams
* @date 2024-01-21 21:36
* @description //TODO 测试
*/
public class CollTest {
  public static void main(String[] args) {
      List<Person> people = Arrays.asList(
              new Person("A", 10),
              new Person("B", 30),
              new Person("C", 21)
      );
      Map<String, Person> peopleByName = people.stream()
              .collect(Collectors.toMap(Person::getName, Function.identity()));
      System.out.println(peopleByName.get("A"));
  }
}
我们使用Persion对象的name值作为key,Function.identity()作为value的转换函数,它会直接返回流中的元素。
Person::getName

就是

Person->Person.getName()
Function.identity()是一个静态方法,它返回一个函数,该函数接受一个参数并返回相同的参数
输出如下:

 

当发生了键冲突。我们可以使用合并函数(oldValue, newValue) -> oldValue + newValue来将相同键的值进行合并。

List<Person> people = Arrays.asList(
        new Person("A", 10),
        new Person("B", 30),
        new Person("A", 21)
);

Map<String, Integer> peopleByName = people.stream()
        .collect(Collectors.toMap(Person::getName, Person::getAge, (key1, key2) -> key1 + key2));

System.out.println(peopleByName);

其中

(key1, key2) -> key1 + key2)

可以简写为

Integer::sum

输出如下:

如果想对其过滤,.filter方法从Stream中筛选出满足指定条件的元素,并返回一个新的Stream对象,如图过滤年龄不为30的人

Map<String, Integer> peopleByName = people.stream()
        .filter(person -> person.getAge()!=30)
        .collect(Collectors.toMap(Person::getName, Person::getAge, (key1, key2) -> key1 + key2));

 

 

暂无评论

发送评论 编辑评论

|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇