博客搬移到这里:http://yemengying.com/
有个本身的博客还蛮好玩的,bazinga!ios
记录一下在工做开发中封装的一些工具类,使代码看起来更加的简洁。这篇就记录下和集合转换相关的吧。。。。。会持续记录。。。。数据结构
开发过程当中常常会碰到须要将list转为map的状况,例若有一个User类,有id,name,age等属性。有一个User的list,为了很方便的获取指定id的User,这时就须要将List< User>转换为Map<Integer,User>,其中map的key是User的id。
通常的作法,是经过for循环将list中的元素put到map中,代码以下:app
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>代码以下code
//省略list构造过程 Map<Integer, User> map = TransFormUtils.transformToMap(userList, p->p.getId(), p->p);
若是须要将List< User>转为Map<Integer,String(用户名)>代码以下orm
//省略list构造过程 Map<Integer, String> map2 = TransFormUtils.transformToMap(userList, p->p.getId(), p->p.getName());
应用封装好的工具类 只须要一行代码就能够完成list到map的转换,程序简单了许多~~开发
将开发中常常须要根据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.利用streamget
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代替Mapio
/** * 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()); }
仍是喜欢第一种哈哈哈哈哈哈~~题外话:既然对现状不满意 就尝试改变吧 虽然有可能进入另外一个坑~~