vue项目接口域名动态的获取方法
2747
2023-06-16
java 三种将list转换为map的方法详解
java 三种将list转换为map的方法详解
在本文中,介绍三种将list转换为map的方法:
1) 传统方法
假设有某个类如下
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();
}
}
使用传统的方法:
@Test
public void convert_list_to_map_with_java () {
List
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map
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直接用流的方法:
@Test
public void convert_list_to_map_with_java8_lambda () {
List
movies.adlHIFrulbd(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map
Collectors.toMap(Movie::getRank, (p) -> p));
logger.info(mappedMovies);
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}
3) 使用guava 工具类库
@Test
public void convert_list_to_map_with_guava () {
List
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map
public Integer apply(Movie from) {
return from.getRank();
}});
logger.info(mappedMovies);
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~