一、导读
本文主要内容包括数组转换成
List
,List
转成数组,List
转成map
的几种方式。好文章 记得 收藏+点赞+关注 !!!
二、代码
/**
* 练习数组转list,list转数组,list转map
*
* @author JiaMing
* @since 2021/12/30/0030 下午 15:22
**/
public class TransformationTest {
public static void main(String[] args) {
//数组转list 方式一
String[] s = new String[]{"hello", "java"};
List<String> list = Arrays.asList(s);
System.out.println(list);
System.out.println("-------------------------------");
//list.add("world");这种方式转换的list 不能对List增删,只能查改,会报错UnsupportedOperationException
为什么会这样?
因为Arrays.asList(s)返回值是java.util.Arrays类中一个私有静态内部类java.util.Arrays.ArrayList,它并非java.util.ArrayList类。
java.util.Arrays.ArrayList类具有 set(),get(),contains()等方法,但是不具有添加add()或删除remove()方法,所以调用add()方法会报错。
//数组转list 方式二 通过集合工具类Collections.addAll()方法
ArrayList<String> arrayList = new ArrayList<>(s.length);
Collections.addAll(arrayList, s);
arrayList.add("world");
System.out.println(arrayList);
System.out.println("-------------------------------");
//list转数组 方式一
String[] strings = new String[arrayList.size()];
arrayList.toArray(strings);
System.out.println(Arrays.toString(strings));
System.out.println("-------------------------------");
//list转数组 方式二 支持泛型的toArray方法
String[] ss = arrayList.toArray(new String[arrayList.size()]);
System.out.println("转换完的数组为:" + Arrays.toString(ss));
List转Map:
/**
* 学生实体类
*
* @author JiaMing
* @since 2021/12/30/0030 下午 15:23
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
/**
* 编号
*/
public Integer id;
/**
* 姓名
*/
public String name;
}
//新建一个ArrayList存放学生对象
ArrayList<Student> studentList = new ArrayList<>();
studentList.add(new Student(1, "佳明"));
studentList.add(new Student(2, "张伟"));
studentList.add(new Student(3, "张三"));
//list转map 方式一
Map<Integer, Student> studentMap = new HashMap<>();
for (Student student : studentList) {
studentMap.put(student.getId(), student);
}
//遍历输出studentMap
studentMap.forEach((K, V) -> System.out.println(K + "," + V));
//list转map 方式二
//编号作为key,名字作为value
//(k1, k2) -> k2)作用是 指定key覆盖规则 防止hash冲突
Map<Integer, String> studentMap2 = studentList.stream().collect(Collectors.toMap(Student::getId, Student::getName, (k1, k2) -> k2));
//遍历输出studentMap
studentMap2.forEach((K, V) -> System.out.println(K + "," + V));
System.out.println("-------------------------------");
//编号作为key,对象作为value
Map<Integer, Student> studentMap3 = studentList.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (k1, k2) -> k2));
studentMap3.forEach((K, V) -> System.out.println(K + "," + V));
System.out.println("-------------------------------");
//list转map 方式三 使用第三方库——Guava库
convertListToMapByGuava(studentList).forEach((K, V) -> System.out.println(K + "," + V));
}
public static Map<Integer, Student> convertListToMapByGuava(List<Student> studentList) {
return Maps.uniqueIndex(studentList, Student::getId);
}
}
OK,表演到此结束!
推荐阅读: