根据指定的实体类中的列名,将List转成Map

本文介绍如何高效地将List中的对象依据指定属性转换为Map,避免逐一遍历。例如,将List<Book>转换为Map<String, Book>,键值对形式如'id-book'或'price-book'。提供了一个示例方法,演示如何实现从List<book>到Map<id, book>的转换,并讨论了基于实体类列名的排序方法。" 125011367,12670975,Redis深度解析:数据结构、持久化、并发控制与实战技巧,"['Redis', '数据结构', '哈希算法', '链表', '开发语言']

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

有时候我们需要从List中查询某一个指定的变量所对应的对象,但是在list中逐个遍历对比不是一个明智的选择。

本篇博客是根据指定的对象中的变量,来将list转换成map,然后直接从map中get即可。

比如,我的list中是book对象。

public class Book {
    
    private Long id;//书本编号
    private String name;//书本名称
    private double price;//书本价格
    private String author;//作者
    private Integer weight;//权重
    
    public Book(Long Id,String Name,double Price,String Author,Integer Weight) {
        this.id=Id;
        this.name=Name;
        this.price=Price;
        this.author=Author;
        this.weight=Weight;
}
}

那么我需要获取指定的id的书本,或者获取指定的价格的书本等。

那么就可以转成map对象,map中的键值对就是  id-book、或者是price-book。

根据指定的键值对转换,方法如下:

第一个是书本类:book:

package userSort;


public class Book {
    
    private Long id;//书本编号
    private String name;//书本名称
    private double price;//书本价格
    private String author;//作者
    private Integer weight;//权重
    
    public Book(Long Id,String Name,double Price,String Author,Integer Weight) {
        this.id=Id;
        this.name=Name;
        this.price=Price;
        this.author=Author;
        this.weight=Weight;
}
    
    
    
    public Long getId() {
        return id;
    }
    
    
    public void setId(Long id) {
        this.id = id;
    }
    
    
    public String getName() {
        return name;
    }
    
    
    public void setName(String name) {
        this.name = name;
    }
    
    
    public double getPrice() {
        return price;
    }
    
    
    public void setPrice(double price) {
        this.price = price;
    }
    
    
    public String getAuthor() {
        return author;
    }
    
    public void setAuthor(String author) {
        this.author = author;
    }
    
    public Integer getWeight() {
        return weight;
    }

    public void setWeight(Integer weight) {
        this.weight = weight;
    }
    
}

第二个文件是转换的文件:这个类的作用就是将根据指定的变量将list转换成map

package ListToMap;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class listToMp {

    @SuppressWarnings("unchecked")
    public static <K, V> Map<K, V> getMapFromListByProperty(List<V> list, String propertyName, Class<K> propertyClass) {
        if (isEmpty(list)) {
            return new HashMap<>();
        }

        Class<?> clz = list.get(0).getClass();
        Map<K, V> resultMap = new HashMap<K, V>(list.size());
        Method mth = getPropertyMethod(clz, propertyName);
        for (Object obj : list) {
            Object value = null;
            try {
                value = mth.invoke(obj);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (value == null) {
                continue;
            }
            resultMap.put(propertyClass.cast(value), (V) obj);
        }
        return resultMap;
    }

    // 判断list是否为空或者为null
    public static <V> boolean isEmpty(List<V> list) {
        if (list.isEmpty() || list == null) return true;
        return false;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Method getPropertyMethod(Class clz, String propertyName) {
        Method mth = null;
        try {
            mth = clz.getMethod(upFirstCharacter(propertyName));
        } catch (Exception e) {
            System.out.println("获取类名发生错误!");
        }
        return mth;

    }

    /**
     * 修改获取名称
     * 
     * @param propertyName
     * @return
     */
    public static String upFirstCharacter(String propertyName) {
        if (propertyName == null || propertyName.isEmpty()) {
            System.out.println("获取类名发生错误!");
            return null;
        }
        char x = propertyName.charAt(0);
        String partOfPropertName = propertyName.substring(1);
        StringBuffer newPropertName = new StringBuffer();
        newPropertName.append("get").append(Character.toUpperCase(x)).append(partOfPropertName);
        propertyName = newPropertName.toString();
        return propertyName;
    }

}


最后一个是测试实现方式,是将list<book>转成map<id,book>的实现方式。

package ListToMap;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import userSort.Book;

public class MainForMap {
    
    public static List<Book> getBookList() {
        List<Book> books = new ArrayList<Book>();
        Book book1 = new Book(1L, "first", 10.00, "zhangsan", 19);
        Book book2 = new Book(2L, "first", 9.00, "zhangsan", 24);
        Book book3 = new Book(3L, "first", 8.00, "zhangsan", 29);
        Book book4 = new Book(4L, "first", 7.00, "zhangsan", 13);
        Book book5 = new Book(5L, "first", 6.00, "zhangsan", 14);

        books.add(book1);
        books.add(book2);
        books.add(book3);
        books.add(book4);
        books.add(book5);

        return books;
    }
    
    public static void main(String[] args) {
        List<Book> books=getBookList();
        Map<Long, Book> bookMap=listToMp.getMapFromListByProperty(books, "id", Long.class);
        for (Long bookvaluse : bookMap.keySet()) {
            System.out.println("Id:" + bookMap.get(bookvaluse).getId() + "\t price: " +  bookMap.get(bookvaluse).getPrice() + "\t weight:" +  bookMap.get(bookvaluse).getWeight());
        }
    }
}


最终的打印结果:

Id:1	 price: 10.0	 weight:19
Id:2	 price: 9.0	 weight:24
Id:3	 price: 8.0	 weight:29
Id:4	 price: 7.0	 weight:13
Id:5	 price: 6.0	 weight:14


可以和我的另一篇文章对比下:

sort 根据实体类中指定的列名对List中的对象进行排序 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值