基础
数组创建
int[] arr = new int[]{11,22,33}; //完整格式
int[] arr = {11,22,33}; //简化格式
int[] arr = new int[5]; //动态初始化格式
增强for循环 [^遍历数组]
//增强for循环(不能直接获得index)
// for((数组元素)数据类型 变量名称:数组名称){
// //变量名称(是数组里面的任意元素)
// }
//遍历数组
int count = 1;
for (int score : studentScore) {//studentScore每个元素依次赋值给score
System.out.println("第" + count + "元素:"+score);
count++;
}
List创建
ArrayList<Integer> list = new ArrayList<>();//初始化容量10
Set创建
HashSet<Integer> hashSet = new HashSet<>();
Map创建
HashMap<Integer, String> hashMap = new HashMap<>();
Java中Array、List、Set、Map之间的各种转换
数组 转 list
//array 转 list
//第一种
String[] arr = new String[] { "a", "b", "c", "d", "e" };//不能增减
List<String> list = Arrays.asList(arr);
//那如果我们想要增删要怎么办?
List<String> list1 = new ArrayList<String>(Arrays.asList(arr));
//第二种
String[] arr = new String[] { "a", "b", "c", "d", "e" }; //可增减
ArrayList<String> list = new ArrayList<String>();
Collections.addAll(list, arr);
数组 转 set
//第一种
String[] str = new String[] { "a", "b", "c", "a" };
Set<String> set = new HashSet<String>(Arrays.asList(str));
//第二种
String[] str = new String[] { "a", "b", "c", "a" };
Set<String> set = new HashSet<String>();
Collections.addAll(set, str);
list 转 数组
Integer[] arr = (Integer[]) list.toArray(new Integer[] {}); //list-数组名称
list 转 set
//第一种
Set<String> set = new HashSet<String>(list);
//第二种
Set<String> set = new HashSet<String>();
set.addAll(list);
list 转 map
List<Student> list = new ArrayList<Student>();
list.add(new Student("111", "一号种子"));
list.add(new Student("222", "二号种子"));
list.add(new Student("333", "三号种子"));
Map<String, Student> map = list.stream().collect(Collectors.toMap(e -> e.id, e -> e));
// 当使用stream流添加的key值存在重复的值的时候,使用上面那种操作会报错,这时候就可以像下面这样
// 简单地添加一个BinaryOperator方法到toMap()中,这也称为合并功能,如果重复,可以取第一个元素
list.add(new Student("111", "重复一号种子"));// 添加的重复键值
Map<String, Student> map1 = list.stream()
.collect(Collectors.toMap(e -> e.id, e -> e, (e1, e2) -> e1));
// 如果想要使用TreeMap对键进行自然排序,或者指定的Map实现呢?如:LinkedHashMap
Map<String, Student> map2 = list.stream().collect(
Collectors.toMap(e -> e.id, e -> e, (e1, e2) -> e1, TreeMap<String, Student>::new));
set 转 list
//第一种
List<String> list = new ArrayList<String>(set);
//第二种
List<String> list = new ArrayList<String>();
list.addAll(set);
map 转 list
// 将Map Key 转化为List
List<String> mapKeyList = new ArrayList<String>(map.keySet());
// 将Map values 转化为List
List<String> mapValuesList = new ArrayList<String>(map.values());
map 转 set
// 将Map Key 转化为set
Set<String> keySet = map.keySet();
// 将Map values 转化为set
HashSet<String> valueSet = new HashSet<String>(map.values());