使代码更简洁(二)----集合转换相关

493 查看

博客搬移到这里:http://yemengying.com/
有个自己的博客还蛮好玩的,bazinga!

记录一下在工作开发中封装的一些工具类,使代码看起来更加的简洁。这篇就记录下和集合转换相关的吧。。。。。会持续记录。。。。

list转map

开发过程中经常会碰到需要将list转为map的情况,例如有一个User类,有id,name,age等属性。有一个User的list,为了很方便的获取指定id的User,这时就需要将List< User>转换为Map<Integer,User>,其中map的key是User的id。
一般的做法,是通过for循环将list中的元素put到map中,代码如下:

Map<Integer, User> map = new HashMap<Integer, User>();
for(User user : userList){
    map.put(user.getId(), user);
}

这样做,在每个需要将list转为map的地方,都要写一遍for循环,代码不够简洁,所以利用stream和泛型封装了一个通用的工具方法

public class TransFormUtils {
    
    /**
     * 将list转为map
     * @param list
     * @param predicate1  key
     * @param predicate2  value
     * @return
     */
    public static<K,V,T>  Map<K, V> transformToMap(List<T> list,Function<T, K> predicate1, Function<T,V> predicate2){
        return list.stream().collect(Collectors.toMap(predicate1, predicate2));
    }

}

这样如果需要将List< User>转为Map<Integer,User>代码如下

//省略list构造过程
Map<Integer, User> map = TransFormUtils.transformToMap(userList, p->p.getId(), p->p);

如果需要将List< User>转为Map<Integer,String(用户名)>代码如下

//省略list构造过程
Map<Integer, String> map2 = TransFormUtils.transformToMap(userList, p->p.getId(), p->p.getName());

应用封装好的工具类 只需要一行代码就可以完成list到map的转换,程序简单了许多~~

list< T >转map< K,List< V>>

将开发中经常需要根据list中的某个属性将list分类。举个例子,在开发通知中心时需要给用户推送消息,安卓和ios是调用的不同的第三方库,所以要根据设备的类型调用不同的方法。首先根据要推送的用户Id列表获得List< DeviceUser>,DeviceUser类的属性包括devicetype,deviceId,userId,userName,createAt等。接着要获得deviceType是ios的deviceId列表,deviceType是安卓的deviceId列表。即将List< DeviceUser>转为Map< Integer,List< String>>,其中map的key是deviceType,value是deviceId的list。
为了解决这个问题,写了一个通用的工具类。
1.利用stream

public class TransFormUtils {
    /**
     * 将list<T>转为Map<K,List<V>>
     * @param list
     * @param predicate1 map中的key
     * @param predicate2 map中的list的元素
     * @return
     */
    public static <K,V,T> Map<K, List<V>> transformToMapList(List<T> list, Function<T, K> predicate1, Function<T,V> predicate2){
        return list.stream().collect(
                Collectors.groupingBy(predicate1, 
                Collectors.mapping(predicate2, 
                        Collectors.toList())));
    }

}

使用如下:

List<DeviceUser> list = new ArrayList<DeviceUser>();
//省略list的构造
Map<Integer, List<String>> deviceMap = TransFormUtils.transformToMapList(list, p->p.getDeviceType(), p->p.getDeviceId());

2.普通方法
同事也写了一个另一个工具类,这种方法定义了一个新的数据结构,直接使用MapList代替Map

/**
 * Map&List组合数据结构
 * 
 * @author jianming.zhou
 *
 * @param <K>
 * @param <V>
 */
public class MapList<K, V> {

    private Map<K, List<V>> map = new HashMap<K, List<V>>();
    
    public List<V> get(K k) {
        return map.get(k);
    }
    
    public void put(K k, V v) {
        if (map.containsKey(k)) {
            map.get(k).add(v);
        } else {
            List<V> list = new ArrayList<V>();
            list.add(v);
            map.put(k, list);
        }
    }
    
    public Set<K> keySet() {
        return map.keySet();
    }
}

使用如下

List<DeviceUser> list = new ArrayList<DeviceUser>();
//省略list的构造
MapList<Integer, List<String>> deviceMap = new MapList<Integer,List< String>>();
for(DeviceUser device : list){
 deviceMap.put(device.getDeviceType(),device.getDeviceId());
}

还是喜欢第一种哈哈哈哈哈哈~~
题外话:既然对现状不满意 就尝试改变吧 虽然有可能进入另一个坑~~