java List转Map

本文介绍了在大数据量查询场景下,如何利用Java将List转换为Map以提高效率。通过批量查询避免连表操作,减少IO请求,提高查询速度。文章提供了JDK和Guava两种实现方式的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在平时的编程过程中,list和map是集合中最常遇到的两种,熟练使用这两种集合是程序员必须具备的技能,list转map的应用常见也是很常遇到的,结合我最近的一个使用场景说一下:

比如我们需要这样的数据  a.id ,a.name b.role 这样的数据,显然这是存在两张表中的,一般我们设计到大数据量的情况下是不会采用连表查询的,连表查询很慢,这个就不多讲了吧。这样我们可以采用批量查询,在a表中查询 a.id ,a.name ,在b表中查询b.id(对应a.id) ,然后封装在两个list中,我们将bList转换为bListMap,在循环中通过key是id相同的,将b.role和a.id,a.name封装在返回类型的bean中。

批量查询的优点还是很明显的,在两个表都是几十万的数据量的情况下,批量查询的时间要比连表查询或者循环查询的时间节省了大概7倍或8倍,这是我亲测的。其中list转map扮演着很重要的角色。将批量查询出的结果在代码层进行组装,还是很快的,因为map的底层是走hash的。而且节省了查库的io请求时间,所以,还是比较快的。

下面是一些具体的使用demo

package test;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Apple {
    private Integer id;
    private String name;
    private BigDecimal money;
    private Integer num;
    public Apple(Integer id, String name, BigDecimal money, Integer num) {
        this.id = id;
        this.name = name;
        this.money = money;
        this.num = num;
    }

    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;
    }

    public BigDecimal getMoney() {
        return money;
    }

    public void setMoney(BigDecimal money) {
        this.money = money;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                ", num=" + num +
                '}';
    }

    public static void main(String[] args) {
        List<Apple> appleList = new ArrayList<Apple>();//存放apple对象集合

        Apple apple1 =  new Apple(1,"苹果1",new BigDecimal("3.25"),10);
        Apple apple12 = new Apple(1,"苹果2",new BigDecimal("1.35"),20);
        Apple apple2 =  new Apple(2,"香蕉",new BigDecimal("2.89"),30);
        Apple apple3 =  new Apple(3,"荔枝",new BigDecimal("9.99"),40);

        appleList.add(apple1);
        appleList.add(apple12);
        appleList.add(apple2);
        appleList.add(apple3);

        /**
         * List -> Map
         * 需要注意的是:
         * toMap 如果集合对象有重复的key,会报错Duplicate key ....
         *  apple1,apple12的id都为1。
         *  可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
         *  1. List转Map
         * id为key,apple对象为value,可以这么做:
         */
        Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1, k2)->k1));
        System.err.println(appleMap);
        // 打印 : {1=Apple{id=1, name='苹果1', money=3.25, num=10}, 2=Apple{id=2, name='香蕉', money=2.89, num=30}, 3=Apple{id=3, name='荔枝', money=9.99, num=40}}

        // 2. 分组
        //List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
        Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
        System.err.println("groupBy:"+groupBy);
        //打印 :groupBy:{1=[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}], 2=[Apple{id=2, name='香蕉', money=2.89, num=30}], 3=[Apple{id=3, name='荔枝', money=9.99, num=40}]}

        // 3. 过滤filter
        //从集合中过滤出来符合条件的元素:
        List<Apple> filterList = appleList.stream().filter(a -> a.getId().equals(1)).collect(Collectors.toList());
        System.err.println("filterList:"+filterList);
        // 打印: filterList:[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}]

        // 4、将集合中的数据按照某个属性求和:
        //计算 总金额
        BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.err.println("totalMoney:"+totalMoney);
        //totalMoney:17.48

        //计算 数量
        int sum = appleList.stream().mapToInt(Apple::getNum).sum();
        System.err.println("sum:"+sum);  //sum:100
        //sum:100
    }

}

上面是JDK的写法(推荐),我们还可以使用guava写法

 Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() {
            @Override
            public Long apply(User user) {
                return user.getId();
            }
   });

 

Java中,将`List`换为`Map`是一个常见的需求,尤其是在处理需要根据某个字段快速查找的对象集合时。以下是一些常用的方法,特别是利用Java 8及更高版本中的Stream API来实现这一换。 ### 使用Java 8 Stream API进行ListMap #### 基本换 对于一个包含多个对象的`List`,如果希望将其换为`Map`,其中键是某个对象属性,值是该对象本身,可以使用`Collectors.toMap()`方法。例如,假设有一个`User`类,它有`getUserId()`方法,可以这样换: ```java Map<Integer, User> userIdAndUser = users.stream() .collect(Collectors.toMap(User::getUserId, user -> user, (oldValue, newValue) -> newValue)); ``` 这里,`User::getUserId`定义了如何从每个`User`对象中提取键,而`user -> user`表示值就是对象本身。当遇到键冲突时,`(oldValue, newValue) -> newValue`定义了如何解决冲突,这里是保留新值[^3]。 #### 自定义合并函数 如果在换过程中可能遇到重复的键,并且需要特定的处理逻辑,可以在`toMap()`方法中提供一个自定义的合并函数。例如,可以选择抛出异常、保留旧值或合并两个值: ```java Map<String, User> userNameAndUser = users.stream() .collect(Collectors.toMap(User::getName, user -> user, (existing, replacement) -> existing)); ``` 在这个例子中,如果发现重复的用户名,将保留已存在的条目[^3]。 ### 使用其他方式ListMap 除了使用Stream API外,还可以通过传统的循环方式手动构建`Map`,虽然这种方式不如Stream API简洁,但在某些特定情况下仍然有用: ```java Map<Integer, User> userIdAndUser = new HashMap<>(); for (User user : users) { userIdAndUser.put(user.getUserId(), user); } ``` 这种方法易于理解和实现,但对于大型数据集来说
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值