java three methods for converting list to map

  • 2020-06-01 09:47:00
  • OfStack

java 3 methods for converting list to map

In this article, there are three ways to convert list to map:

1) traditional methods

Let's say I have a class that looks like this


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

Using traditional methods:


@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) direct streaming of JAVA 8:


@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) use the guava tool library


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

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: