Java8 stream特性:Collectors.toMap

package stream;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author zzl
 * @Date 2022/1/15
 * @description Java stream特性:Collectors.toMap
 */
public class CollectorsToMapTest {
    public static void main(String[] args) {
        List<TestVo> testList = new ArrayList<>();
        // 初始化list
        for (int i = 0; i < 3; i++) {
            TestVo vo = new TestVo();
            vo.setUserId(i);
            vo.setName(UUID.randomUUID().toString().replaceAll("-", ""));
            testList.add(vo);
        }
        // toMap(p1,p2),p1参数是map的key值,p2参数是map的value值,当value为对象时,可以用Function.identity()表示value值
        Map<Integer, String> map = testList.stream().collect(Collectors.toMap(TestVo::getUserId, TestVo::getName));

        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());
        }
        System.out.println("==================================================");

        testList = new ArrayList<>();
        testList.add(new TestVo(1, "a"));
        testList.add(new TestVo(2, "b"));
        testList.add(new TestVo(1, "c"));
        // toMap(p1,p2,p3),其中p3参数是为了解决key值冲突时,决定value取值的
        Map<Integer, String> map2 = testList.stream()
                .collect(Collectors.toMap(TestVo::getUserId, TestVo::getName, (oldValue, newValue) -> oldValue));

        System.out.println("(oldValue, newValue) -> oldValue的方式:key值冲突时,value取值为旧的key对应的value值");
        map2.forEach((k, v) -> System.out.println("key=" + k + ",value=" + v));

        System.out.println("(oldValue, newValue) -> newValue的方式:key值冲突时,value取值为新的key对应的value值");
        map2 = testList.stream()
                .collect(Collectors.toMap(TestVo::getUserId, TestVo::getName, (oldValue, newValue) -> newValue));
        map2.forEach((k, v) -> System.out.println("key=" + k + ",value=" + v));
    }
}

执行结果 :

key=0,value=acd45a638a2b43a4b7ccab7781290916
key=1,value=6fa7e201faaf4de0b4d6645214966285
key=2,value=468721a42ff14dc38a0b4efd2bf288eb
==================================================
(oldValue, newValue) -> oldValue的方式:key值冲突时,value取值为旧的key对应的value值
key=1,value=a
key=2,value=b
(oldValue, newValue) -> newValue的方式:key值冲突时,value取值为新的key对应的value值
key=1,value=c
key=2,value=b
package stream;


/**
 * @author zzl
 * @Date 2022/1/15
 * @description
 */
public class TestVo {
    private Integer userId;
    private String name;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public TestVo(Integer userId, String name) {
        this.userId = userId;
        this.name = name;
    }

    public TestVo() {

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java8中,我们可以使用Stream API来对集合进行分组、排序等操作,其中Collectors.groupingBy是一个非常有用的方法。它接收一个Function作为参数,用于将元素映射为分组的键,返回一个Map类型的结果,其中键是由Function映射的结果,值是对应的元素列表。 例如,我们有一个Person类,其中包含姓名和年龄两个属性,我们想按照年龄进行分组: ``` List<Person> persons = Arrays.asList( new Person("John", 30), new Person("Jane", 25), new Person("Bob", 40), new Person("Mary", 35) ); Map<Integer, List<Person>> personsByAge = persons.stream() .collect(Collectors.groupingBy(Person::getAge)); personsByAge.forEach((age, list) -> System.out.println(age + " -> " + list)); ``` 输出结果为: ``` 25 -> [Person{name='Jane', age=25}] 30 -> [Person{name='John', age=30}] 35 -> [Person{name='Mary', age=35}] 40 -> [Person{name='Bob', age=40}] ``` 我们还可以对分组结果进行排序,例如按照年龄从小到大排序: ``` Map<Integer, List<Person>> personsByAgeSorted = persons.stream() .collect(Collectors.groupingBy(Person::getAge, TreeMap::new, Collectors.toList())); personsByAgeSorted.forEach((age, list) -> System.out.println(age + " -> " + list)); ``` 输出结果为: ``` 25 -> [Person{name='Jane', age=25}] 30 -> [Person{name='John', age=30}] 35 -> [Person{name='Mary', age=35}] 40 -> [Person{name='Bob', age=40}] ``` 在这个例子中,我们使用TreeMap作为分组结果的容器,实现了按照年龄从小到大排序的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值