集合间互相转化
2016-03-20 11:48
429 查看
Java8之前集合之间互相转化,例如List -> Map需要写许多代码,但是Java8之后可以使用Lambda表达式简化代码。
示例:
1.List<T> ---> Map<K, V>
使用Lambda表达式简化后:
2.List<T> ---> Map<K, List<T>>
3.List<T> ---> List<R>
4.List<T> ---> Set<R>
示例:
1.List<T> ---> Map<K, V>
List<String> list = Arrays.asList("zero"); Map<String, Integer> map = list.stream().collect( Collectors.toMap(new Function<String, String>() { @Override public String apply(String e) { return e; } }, new Function<String, Integer>() { @Override public Integer apply(String e) { return e.hashCode(); } }));示例中,Collectors.toMap接收两个Function参数,第一个Function是生成key,第二个Function是生成value,两个Function<T,X>的第一个泛型参数类型是对应的list的类型,这里即是String。
使用Lambda表达式简化后:
List<String> list = Arrays.asList("zero"); Map<String, Integer> map = list.stream().collect( Collectors.toMap(e -> e, e -> e.hashCode()));
2.List<T> ---> Map<K, List<T>>
List<String> list = Arrays.asList("zero", "world", "hello"); Map<Integer, List<String>> map = list.stream().collect( Collectors.groupingBy(e -> e.length())); //{4=[zero], 5=[world, hello]}
3.List<T> ---> List<R>
List<String> list = Arrays.asList("zero", "hi"); List<Integer> list2 = list.stream().map(e -> e.hashCode()).collect(Collectors.toList()); //[3735208, 3329]
4.List<T> ---> Set<R>
List<String> list = Arrays.asList("zero", "hello", "world"); Set<Integer> set = list.stream().map(e -> e.length()).collect(Collectors.toSet()); //[4, 5]
相关文章推荐
- linux 网络源码布局
- dw子数据窗口dddw自动检索数据
- javaweb——登陆权限过滤器的编写
- 第四周项目4:理解函数的默认参数
- juniper SRX防火墙和cisco 交换机链路聚合配置
- LightOJ 1245 - Harmonic Number (II) (找规律)
- Kafka学习之四 Kafka常用命令
- 批处理教程(1)
- CoreMotion的实际使用,主要获得加速度或者手机朝向
- Java用wait() notify()实现线程间通信
- 辩数字
- 【VB.NET】常用函数概览
- 24.NSURLConnection与RunLoop
- 《iOS Human Interface Guidelines》——Web View
- <转>python 发送邮件实例
- linux安全第四周总结
- 谁是小偷
- UVA 11825 Hackers' Crackdown - 状压dp
- PB中取得数据窗口所有列名以及列标题名称
- Activity中finish() onDestroy() 和System.exit()的区别