• list,set,map,数组之间的相互转换详细解析


    1.list转set
    Set set = new HashSet(new ArrayList()); 

    2.set转list
    List list = new ArrayList(new HashSet());

    3.数组转为list
    List stooges = Arrays.asList("Larry", "Moe", "Curly");

    或者
    String[] arr = {"1", "2"};
    List list = Arrays.asList(arr);

    4.数组转为set
    int[] a = { 1, 2, 3 };

    Set set = new HashSet(Arrays.asList(a));

    5.map的相关操作。
    Map map = new HashMap();

    map.put("1", "a");
    map.put('2', 'b');
    map.put('3', 'c');
    System.out.println(map);
    // 输出所有的值
    System.out.println(map.keySet());
    // 输出所有的键
    System.out.println(map.values());
    // 将map的值转化为List
    List list = new ArrayList(map.values());
    System.out.println(list);
    // 将map的值转化为Set
    Set set = new HashSet(map.values());
    System.out.println(set);

    6.list转数组
    List list = Arrays.asList("a","b");

    String[] arr = (String[])list.toArray(new String[list.size()]);
    System.out.println(Arrays.toString(arr));

    //1.数组转换为list,map 
    String[] arr = {"123","456","789","123"}; 
    List<String> list = Arrays.asList(arr); 
    //数组转换为map,一维数组时,奇数为key,偶数为value,奇数个元素,最后一个舍掉 
    //.二维数组当做两个一维数组 
    Map map = MapUtils.putAll(new HashMap(), arr); 

    String[][] ss = {{"a","b","e"},{"c","d","f"}}; 
    MapUtils.debugPrint(System.out,arr,map); 
    MapUtils.putAll(map, arr); 
    MapUtils.debugPrint(System.out,arr,map); 
    MapUtils.putAll(map, ss); 
    MapUtils.verbosePrint(System.out,arr,MapUtils.invertMap(map)); 

    //list 转换为arr 
    List<String> ls = new ArrayList<String>(); 
    ls.add("wch"); 
    ls.add("name"); 
    String[] as = (String[]) ls.toArray(); 

    /**
     * List<Map<Object,Object>> to 二维数组
     * @param list
     * @param keyLength - Map中的key个数
     * @return
     */
    public static Object[][] list2array(List<Map<Object,Object>> list,int keyLength){
        Object[][] array = new Object[list.size()][keyLength];
        for(int i=0;i<list.size();i++){
            array[i] = list.get(i).values().toArray();
        }
        return array;
    }
  • 相关阅读:
    soap-学习
    Redis教程
    Java 不可变对象
    java volatile
    Go语言
    mongodb 基础语法
    Linux 命令大全
    Java json字符串对比
    sqlserver 数据库阻塞和死锁
    http 和 https 的区别
  • 原文地址:https://www.cnblogs.com/androidsj/p/5615312.html
Copyright © 2020-2023  润新知