1. 程式人生 > >根據指定的實體類中的列名,將List轉成Map

根據指定的實體類中的列名,將List轉成Map

有時候我們需要從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


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