继承之前的一篇:?从非诚勿扰看数据索引,优化代码小妙招
直接将这个实用小算法封装成一个工具类。
public?class?IndexUtil {
/**
?* List转Map
?* @param list 原始列表数据(任何实现List接口的数据)
?* @param keyExtractor (抽取Key值的方法)
?* @return 加了索引的数据->Map
?*/
public?static <K,V> Map<K,V> fromList(List<V> list,Function<V,K> keyExtractor){
????????Map<K,V> result = new?HashMap<K, V>();
????????for?(Iterator<V> iterator = list.iterator(); iterator.hasNext();) {
????????????????V v = (V) iterator.next();
????????????????K extractorKey = keyExtractor.extractor(v);
????????????????if(extractorKey == null) {
????????????????????????continue;
????????????????}
????????result.put(extractorKey, v);
}
????????return?result;
}
public?static void?main(String[] args) {
????????User?user?= new?User();
????????user.setUserName("A");
????????user.setPassword("1233544");
????????List<User> userList = new?ArrayList<User>();
????????userList.add(user);
????????user?= new?User();
????????user.setUserName("B");
????????user.setPassword("3r43");
????????userList.add(user);
????????user?= new?User();
????????user.setUserName("C");
????????user.setPassword("t5y6y");
????????userList.add(user);
????????Map<String, User> fromList = IndexUtil.fromList(userList, new?Function<User, String>() {
????????????????@Override
????????????????public?String extractor(User?v) {
????????????????????????return?v.getUserName();
????????????????}
????????});
????????????????System.out.println(fromList.get("C").getPassword());
????????}
}
Function是一个抽取Key值的接口,因为JDK1.6没有lamda表达式,所以只能用内部类了。
public?interface?Function<V,K> {
????????K extractor(V v);
}
亲测有效,代码中这种情况还是挺多的,用工具类可以省去很多重复代码。
|