1) 传统方法

假设有某个类如下

Java代码

class Movie {  

    private Integer rank;
private String description; public Movie(Integer rank, String description) {
super();
this.rank = rank;
this.description = description;
} public Integer getRank() {
return rank;
} public String getDescription() {
return description;
} @Override
public String toString() {
return Objects.toStringHelper(this)
.add("rank", rank)
.add("description", description)
.toString();
}
}

1、使用传统的方法:

public void convert_list_to_map_with_java () {  

    List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather")); Map<Integer, Movie> mappedMovies = new HashMap<Integer, Movie>();
for (Movie movie : movies) {
mappedMovies.put(movie.getRank(), movie);
} logger.info(mappedMovies); assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}

2、JAVA 8直接用流的方法

public void convert_list_to_map_with_java8_lambda () {  

    List<Movie> movies = new ArrayList<Movie>();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather")); Map<Integer, Movie> mappedMovies = movies.stream().collect(
Collectors.toMap(Movie::getRank, (p) -> p)); logger.info(mappedMovies); assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}

(2)转换过程中的两个问题

a、key重复

重复时用后面的value 覆盖前面的value

Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key2 ));

重复时将前面的value 和后面的value拼接起来

Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key1+","+key2 ));

重复时将重复key的数据组成集合

Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
));

b、valve为null

在转换流中加上判空,即便value为空,依旧输出

Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
return value1;
}
))

3、使用guava 工具类库

public void convert_list_to_map_with_guava () {  

    List<Movie> movies = Lists.newArrayList();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather")); Map<Integer,Movie> mappedMovies = Maps.uniqueIndex(movies, new Function <Movie,Integer> () {
public Integer apply(Movie from) {
return from.getRank();
}}); logger.info(mappedMovies); assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}

--------------------------------------------------------------------------------------------------------------------------------------------------------------------**  分隔符  **--------------------------------------------------------------------------------------------------------------------------------------------------------------------

一、
list转map
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));

二、
另外,转换成map的时候,可能出现key一样的情况,如果不指定一个覆盖规则,上面的代码是会报错的。转成map的时候,最好使用下面的方式:
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));

三、
有时候,希望得到的map的值不是对象,而是对象的某个属性,那么可以用下面的方式:
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));

四、
//List 以ID分组 Map<Integer,List>
Map<Integer, List> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

System.err.println(“groupBy:”+groupBy);
{1=[Apple{id=1, name=‘苹果1’, money=3.25, num=10}, Apple{id=1, name=‘苹果2’, money=1.35, num=20}], 2=[Apple{id=2, name=‘香蕉’, money=2.89, num=30}], 3=[Apple{id=3, name=‘荔枝’, money=9.99, num=40}]}

最新文章

  1. 由表单验证说起,关于在C#中尝试链式编程的实践
  2. Java中是否可以调用一个类中的main方法?
  3. [css]水平垂直居中的方法
  4. 编译WebRTC遇到的问题总结
  5. Hive安装
  6. Android Studio NDK 学习之接受Java传入的字符串
  7. HDU 5754 Life Winner Bo (各种博弈) 2016杭电多校联合第三场
  8. c语言学习的第6天
  9. delphi 网络函数
  10. C++输出中文字符(转)
  11. Python语言在企业级应用上的十大谬误
  12. WindowsPE权威指南 第二章 小工具 pedump代码的C语言实现
  13. MySQL&#160;横向表分区之RANGE分区小结
  14. 3ds max学习笔记(二)--查看视点
  15. python实现文件下载图片视频
  16. Python -----issubclass和isinstance
  17. 浅谈sql中的in与not in,exists与not exists的区别以及性能分析
  18. iOS获取ipa素材、提取ipa资源图片文件
  19. td自动换行
  20. url添加时间戳

热门文章

  1. 080_Dataloader.io
  2. vue封装组件
  3. 前端实现电子签名(web、移动端)通用组件
  4. Libusb测试USB device(2)
  5. 【vcpkg】使用vcpkg安装库
  6. nodeJs 写个爬虫小玩意
  7. android判断是否连接wifi跟网络状态的判断及wifi信号强度的方法
  8. h5 json 生成excel
  9. 2022NCTF
  10. vscode 远程连接 linux 远程开发