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]);
- 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());
阅读全文
0 0
- Java中集合与数组互转总结
- Java中集合与数组
- Java中集合与数组
- java中集合与数组的区别
- java中集合总结
- JAVA中集合总结
- Java中集合总结
- JAVA中集合总结
- java中集合的总结
- java中集合的总结
- java中集合与数组之间的转化
- java中集合与数组之间的转化
- java中集合与数组之间的转化
- java中集合与数组之间的转化
- Java中集合类用法总结(转)
- C#中集合与数组的区别
- Java中集合和数组的区别
- java中集合类的总结
- Eclipse下修改java文件默认编译路径
- 转载:Introducing the Software Testing Cupcake (Anti-Pattern)
- URI和URL的区别
- babel-polyfill让你放心用es6做开发
- spring 框架配置类
- Java中集合与数组互转总结
- JSONP跨域,CORS跨域,Hybrid APP跨域
- css类选择器使用
- 电商笔记-08(Reids展示品牌名称与价格排序简单算法.PS:特绕)
- 【安全牛学习笔记】ACUNETIX WEB VULNERABILITY SCANNER
- 文章标题
- Xcode使用系统工具自动增加version number
- 解决 div或者a标签的高度比里面的img高度多了5px 问题
- CSS外边距及盒子居中对齐