List怎样和Map互相转化
来源:4-2 Map实现类—HashMap与LinkedHashMap的区别
何艾莉
2022-09-17 20:11:24
老师好,List怎样和Map互相转化,能不能提供一下代码讲解,我今天面试问到了。我回答不出,谢谢老师的回答。
1回答
好帮手慕小小
2022-09-18
同学你好,代码实现方式不唯一,可参考如下代码实现:
使用for循环:
public class ListToMap { public static void main(String[] args) { List<Movie> movies = new ArrayList<Movie>(); movies.add(new Movie(1009, "MOVIE_1")); movies.add(new Movie(1100, "MOVIE_2")); Map<Integer, Movie> mappedMovies = new HashMap<Integer, Movie>(); for (Movie movie : movies) { mappedMovies.put(movie.getId(), movie); } //遍历 mappedMovies.forEach((key, value) -> System.out.println(key + "," + value)); } } class Movie { private Integer id; private String description; public Movie(Integer id, String description) { super(); this.id = id; this.description = description; } public Integer getId() { return id; } public String getDescription() { return description; } @Override public String toString() { return "Movie{" + "rank=" + id + ", description='" + description + '\'' + '}'; } }
使用Stream:
public class ListToMap { public static void main(String[] args) { List<Movie> movies = new ArrayList<Movie>(); movies.add(new Movie(1009, "MOVIE_1")); movies.add(new Movie(1100, "MOVIE_2")); Map<Integer, Movie> mappedMovies = movies.stream().collect( Collectors.toMap(Movie::getId, p -> p)); //遍历 mappedMovies.forEach((key, value) -> System.out.println(key + "," + value)); } } class Movie { private Integer id; private String description; public Movie(Integer id, String description) { super(); this.id = id; this.description = description; } public Integer getId() { return id; } public String getDescription() { return description; } @Override public String toString() { return "Movie{" + "rank=" + id + ", description='" + description + '\'' + '}'; } }
Map转List参考代码:
//Map转为List Set<Map.Entry<Integer, Movie>> entrySet = mappedMovies.entrySet(); List<Map.Entry<Integer, Movie>> list1 = new ArrayList<>(); for (Map.Entry<Integer,Movie> entry : entrySet){ list1.add(entry); } System.out.println(list1); List<Map.Entry<Integer, Movie>> list2 = new ArrayList<>(); entrySet.forEach(entry -> list2.add(entry)); System.out.println(list2);
祝学习愉快~
相似问题