publicvoidListToMap(){ System.out.println("ListToMap"); Map<Object, Object> map = new HashMap<>(); List<String> list = new ArrayList<>(); list.add("布朗克斯"); list.add("布鲁克林"); list.add("曼哈顿"); list.add("皇后区"); list.add("斯塔滕岛"); //方法一 for (int i = 0; i < list.size(); i++) { map.put("第" + i + 1 + "区", list.get(i)); } System.out.println(map); //方法二 List<Book> bookList = new ArrayList<>(); bookList.add(new Book("平凡的世界", 2004, "9787020048045")); bookList.add(new Book("战争与和平", 1989, "9787020014071")); bookList.add(new Book("百年孤独", 1775, "9787215069657")); for (int i = 0; i < bookList.size(); i++) { System.out.println(bookList.get(i).toString()); } Map<String, Integer> map1 = bookList.stream().collect(Collectors.toMap(Book::getName, Book::getReleaseYear)); System.out.println(map1);
}
ListToSet
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicvoidListToSet(){ System.out.println("ListToSet"); Set<Object> set = new HashSet<>(); List<String> list = new ArrayList<>(); list.add("布朗克斯"); list.add("布鲁克林"); list.add("曼哈顿"); list.add("皇后区"); list.add("斯塔滕岛"); for (Object i : list) { set.add(i); } System.out.println(set); }
publicvoidSetToArray(){ System.out.println("SetToArray"); Set<Object> set = new HashSet<>(); set.add("北京"); set.add("上海"); set.add("深圳"); set.add("广州"); Object[] objects = set.toArray(new Object[set.size()]); System.out.println(Arrays.toString(objects)); }
SetToList
1 2 3 4 5 6 7 8 9 10
publicvoidSetToList(){ System.out.println("SetToList"); Set<Object> set = new HashSet<>(); set.add("北京"); set.add("上海"); set.add("深圳"); set.add("广州"); List<Object> list = new ArrayList<>(set); System.out.println(list); }
SetToMap
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicvoidSetToMap(){ System.out.println("SetToMap"); Set<Object> set = new HashSet<>(); set.add("北京"); set.add("上海"); set.add("深圳"); set.add("广州"); Map<Object, Object> map = new HashMap<>(); Iterator iterator = set.iterator(); for (int i = 0; i < set.size(); i++) { map.put(i, iterator.next()); } System.out.println(map); }