javalist转map_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() {
StringHelper(this)
.add("rank", rank)
.
add("description", description)
.toString();
}
}
使⽤传统的⽅法:
@Test
public void convert_list_to_map_with_java () {
List movies = new ArrayList();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map mappedMovies = new HashMap();
for (Movie movie : movies) {
mappedMovies.Rank(), movie);
}
logger.info(mappedMovies);
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", (1).getDescription()); }
2) JAVA 8直接⽤流的⽅法:
@Test
public void convert_list_to_map_with_java8_lambda () {
List movies = new ArrayList();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map mappedMovies = movies.stream().collect(
logger.info(mappedMovies);
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", (1).getDescription()); }
3) 使⽤guava ⼯具类库
@Test
public void convert_list_to_map_with_guava () {
List movies = wArrayList();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
Map mappedMovies = Maps.uniqueIndex(movies, new Function () {
public Integer apply(Movie from) {
Rank();
}});
logger.info(mappedMovies);
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", (1).getDescription()); }
感谢阅读,希望能帮助到⼤家,谢谢⼤家对本站的⽀持!
java的tostring方法

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。