Skip to content

Instantly share code, notes, and snippets.

@justinmusgrove
Created September 3, 2013 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justinmusgrove/6431155 to your computer and use it in GitHub Desktop.
Save justinmusgrove/6431155 to your computer and use it in GitHub Desktop.
ConvertListToMap.java
@Test
public void test_convertListToMap () {
// create a list
List<Movie> movies = Lists.newArrayList();
movies.add(new Movie(1, "The Shawshank Redemption"));
movies.add(new Movie(2, "The Godfather"));
// convert list to map
Map<Integer,Movie> mappedMovies = Maps.uniqueIndex(movies, new Function <Movie,Integer> () {
public Integer apply(Movie from) {
return from.getRank(); // or something else
}});
assertTrue(mappedMovies.size() == 2);
assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}
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;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment