# 集合转换和实用操作

1.数组转换成字符串

``````int[] arr = {1,2,3,4};
String str= Arrays.stream(arr).boxed().map(Object::toString).collect(Collectors.joining(","));
``````

2.集合转换成字符串

``````Integer[] arr = {1,2,3,4};
List<Integer> list = Arrays.asList(arr);
String str = list.stream().map(Object::toString).collect(Collectors.joining(","));
``````

3.集合交集、并集、补集、差集

``````//并集
Collection<String> union = CollectionUtils.union(listA, listB);
System.out.println("并集："+union);
//交集
Collection<String> intersection = CollectionUtils.intersection(listA, listB);
System.out.println("交集："+intersection);
//交集的补集
Collection<String> disjunction = CollectionUtils.disjunction(listA, listB);
System.out.println("交集的补集   ："+disjunction);
//差集(集合相减)
Collection<String> subtract = CollectionUtils.subtract(listA, listB);
System.out.println("差集(集合相减)   ："+subtract);
``````

4.list集合分组

``````// 多字段分组
Map<String, List<T>> workflowMapList = t.stream().collect(Collectors.groupingBy(w -> w.getField1().concat(w.getField2())));
// 单子段分组
Map<String, List<T>> workflowMapList = t.stream().collect(Collectors.groupingBy(T::getField1));
// 取其中的某个字段
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Entity::getId, Entity::getType));

/**
* List<T> -> Map<Object,T>
* 需要注意的是：
* toMap 如果集合对象有重复的key，会报错Duplicate key ....
* apple1,apple12的id都为1。
* 可以用 (k1,k2)->k1 来设置，如果有重复的key,则保留key1,舍弃key2
*/
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
``````

5.排序

``````// 默认字符排序
Collections.sort(listStr);
// 对象单个排序
itemList.sort(Comparator.comparing(item::getA));
// 多字段排序：a b 都是对象的属性
itemList.sort(Comparator.comparing(item::getA).thenComparing(item::getB));
``````