# 三种将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)
.toString();
}
}

```

使用传统的方法：

```
@Test
public void convert_list_to_map_with_java () {

List<Movie> movies = new ArrayList<Movie>();

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直接用流的方法：

```
@Test
public void convert_list_to_map_with_java8_lambda () {

List<Movie> movies = new ArrayList<Movie>();

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 工具类库

```
@Test
public void convert_list_to_map_with_guava () {

List<Movie> movies = Lists.newArrayList();

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());
}
```

• 0

开心

• 0

板砖

• 0

感动

• 0

有用

• 0

疑问

• 0

难过

• 0

无聊

• 0

震惊

1.Maven工程中主要添加的依赖 <!--处理excel、word--> <dependency> <groupId>or
1.Maven工程中主要添加的依赖 <!--处理excel、word--> <dependency> <groupId>or