服务器之家

服务器之家 > 正文

java 三种将list转换为map的方法详解

时间:2020-07-31 15:50     来源/作者:lqh

java 三种将list转换为map的方法详解

 在本文中,介绍三种将list转换为map的方法:

1) 传统方法

假设有某个类如下 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
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直接用流的方法:  

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
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());
}

3) 使用guava 工具类库 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
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());
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享
歪歪漫画vip账号共享2020_yy漫画免费账号密码共享 2020-04-07
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
男生常说24816是什么意思?女生说13579是什么意思?
男生常说24816是什么意思?女生说13579是什么意思? 2019-09-17
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意
沙雕群名称大全2019精选 今年最火的微信群名沙雕有创意 2019-07-07
返回顶部