Java 集合转换(数组、List、Set、Map相互转换)
- package com.example.test;
-
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
-
- public class ConvertorTest {
-
-
- public static void main(String[] args) {
-
- testList2Array();
- testArray2List();
- testSet2List();
- testList2Set();
- testSet2Array();
- testArray2Set();
- testMap2Set();
- testMap2List();
- }
-
- private static void testMap2List() {
-
- Map map = new HashMap();
- map.put("A", "ABC");
- map.put("K", "KK");
- map.put("L", "LV");
-
-
- List mapKeyList = new ArrayList(map.keySet());
- System.out.println("mapKeyList:"+mapKeyList);
-
-
- List mapValuesList = new ArrayList(map.values());
- System.out.println("mapValuesList:"+mapValuesList);
-
- }
-
- private static void testMap2Set() {
-
- Map map = new HashMap();
- map.put("A", "ABC");
- map.put("K", "KK");
- map.put("L", "LV");
-
-
- Set mapKeySet = map.keySet();
- System.out.println("mapKeySet:"+mapKeySet);
-
-
- Set mapValuesSet = new HashSet(map.values());
- System.out.println("mapValuesSet:"+mapValuesSet);
- }
-
- private static void testArray2Set() {
-
- String[] arr = {"AA","BB","DD","CC","BB"};
-
-
- Set set = new HashSet(Arrays.asList(arr));
- System.out.println(set);
- }
-
- private static void testSet2Array() {
- Set set = new HashSet();
- set.add("AA");
- set.add("BB");
- set.add("CC");
-
- String[] arr = new String[set.size()];
-
- set.toArray(arr);
- System.out.println(Arrays.toString(arr));
- }
-
- private static void testList2Set() {
-
- List list = new ArrayList();
- list.add("ABC");
- list.add("EFG");
- list.add("LMN");
- list.add("LMN");
-
-
- Set listSet = new HashSet(list);
- System.out.println(listSet);
- }
-
- private static void testSet2List() {
-
- Set set = new HashSet();
- set.add("AA");
- set.add("BB");
- set.add("CC");
-
-
- List setList = new ArrayList(set);
- System.out.println(setList);
- }
-
- private static void testList2Array() {
-
- List list = new ArrayList();
- list.add("AA");
- list.add("BB");
- list.add("CC");
- Object[] objects = list.toArray();
- System.out.println("objects:"+Arrays.toString(objects));
-
- String[] arr = new String[list.size()];
- list.toArray(arr);
- System.out.println("strings1:"+Arrays.toString(arr));
- }
-
- private static void testArray2List() {
-
- String[] ss = {"JJ","KK"};
- List list1 = Arrays.asList(ss);
- List list2 = Arrays.asList("AAA","BBB");
- System.out.println(list1);
- System.out.println(list2);
- }
-
- }