1 List -> Map
设个User类:
public class User {
private String userName;
private String userId;
private String userInfo;
public User(){}
public User(String userName, String userId, String userInfo) {
this.userName = userName;
this.userId = userId;
this.userInfo = userInfo;
}
//getter setter
}
1)foreach()方法
//foreach
public Map<String,User> ltmForEach(List<User> list){
Map<String,User> map = new HashMap<>();
list.forEach(user -> {
map.put(user.getUserId(), user);
});
return map;
}
2)collect()方法
//collect()
public Map<String,User> ltmStream(List<User> list){
/**
* Collectors.toMap()方法参数:
* keyMapper: User::getUserId,调用User的getter方法
* valueMapper: user->user, User类作为value
* mergeFunction: 当key冲突时,value合并的方法:(n1,n2)->n2为替换,(n1,n2)->n1+n2为累加
* mapSupplier: Map构造器,需要返回特定Map的时候使用,如TreeMap::new返回以key排序的Map
*/
return list.stream()
.collect(Collectors.toMap(User::getUserId,user->user,(n1,n2)->n2,TreeMap::new));
}
3)Map常用遍历方法
// 1. 增强for循环
Map<String, User> ltmStreamMap = l.ltmStream(list);
for(Map.Entry entry : ltmStreamMap.entrySet()){
System.out.println(entry.getKey()+" : "+entry.getValue());
}
// 2. Iterator迭代器
Map<String, User> ltmForEachMap = l.ltmForEach(list);
Iterator<Map.Entry<String, User>> iterator = ltmForEachMap.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry<String, User> next = iterator.next();
System.out.println(next.getKey()+" : "+next.getValue());
}
// 3. 内循环
Map<String, User> ltmForEachMap = l.ltmForEach(list);
ltmForEachMap.forEach((k,v)->{
System.out.println(k+" : "+v);
});
2 Array -> List
Array指数组类型数据,如:String[]、Object[]、int[]等
一般使用工具类Arrays的asList方法:
public class arrayToList {
public static void main(String[] args) {
String[] strs = new String[]{"a","b","c"};
List<String> list = Arrays.asList(strs);
for(String str : list){
System.out.println(str);
}
}
}
3 List -> Array
集合List转为数组类型Array
通常使用Collection的toArray方法
public class listToArray {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
//List->Array,申请大小为list.size()的数组空间
String[] strs = list.toArray(new String[list.size()]);
}
}
4 Array <-> Set
public class arrayToSet {
public static void main(String[] args) {
/**
* Array数组类型转为Set类型集合
* 需要Array->List->Set
*/
String[] strs = new String[]{"a","b","c"};
Set<String> set = new HashSet<>(Arrays.asList(strs));
/**
* Set转为Array和List转为Array原理相同
*/
strs = set.toArray(new String[set.size()]);
}
}
5 List <-> Set
List和Set都实现了Collection借口,Collection.addAll()方法
相互转换可以通过:
1)Collection.addAll()
2)构造方法直接传入List/Set
/** * List -> Set
*/
Set set = new HashSet(list);//构造传参
set.addAll(list);//Collection.addAll()
/**
* Set -> List
*/
List list = new ArrayList(set);
list.addAll(set);