Java中集合与数组互转总结

来源:互联网 发布:儋州市政务网通知公布 编辑:程序博客网 时间:2024/05/22 08:05

1.集合之间,以及集合与数组互转

1.List转换为ArrayList<String> list = new ArrayList<String>();list.add(“1”);list.add(“2”);list.add(“3”);list.add(“4”);String [] countries = list.toArray(new String[list.size()]);2.Array转换为ListString[] countries = {“1”, “2”, “3”, “4”};List list = Arrays.asList(countries);3.Map转换为ListList<Value> list = new ArrayList<Value>(map.values());4.Array转换为SetString [] countries = {“1”, “2”, “3”};      Set<String> set = new HashSet<String>(Arrays.asList(countries));System.out.println(set);5.Map转换为SetMap<Integer, String> sourceMap = createMap();Set<String> targetSet = new HashSet<>(sourceMap.values());

特别说明:

  • 采用集合的toArray()方法直接把List集合转换成数组,这里需要注意,不能这样写: 
    String[] array = (String[]) mlist.toArray(); 
    这样写的话,编译运行时会报类型无法转换java.lang.ClassCastException的错误,这是为何呢,这样写看起来没有问题啊 
    因为java中的强制类型转换是针对单个对象才有效果的,而List是多对象的集合,所以将整个List强制转换是不行的 
    正确的写法应该是这样的 
    String[] array = mlist.toArray(new String[0]);
    List<String> mlist = new ArrayList<>();    mlist.add("zhu");    mlist.add("wen");    mlist.add("tao");    // List转成数组    String[] array = mlist.toArray(new String[0]);    // 输出数组    for (int i = 0; i < array.length; i++) {        System.out.println("array--> " + array[i]);    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11


2.List<T>转List<String>最佳方法

使用Google的Lists工具类

eg:

    List<Integer>转List<String>

import com.google.common.collect.Lists;import com.google.common.base.FunctionsList<Integer> integers = Arrays.asList(1, 2, 3, 4);List<String> strings = Lists.transform(integers, Functions.toStringFunction());









原创粉丝点击