Map转换为List
三种Map:包含 Map
>, Map
,stream
>, Map
,stream
1、Map
>
>
package CSDN; import java.util.*; import java.util.function.Function; / * 2021/12/8 22:15 */ public class MapToList {
public static void main(String[] args) {
// 包含匿名方法的map转换成list,结果是hashCode(猜测是) Map<String, Function<Integer, Void>> funMap = mapIncludeFun(); List<Function<Integer, Void>> listFun = new ArrayList<>(); for (Map.Entry<String, Function<Integer, Void>> map : funMap.entrySet()) {
listFun.add(map.getValue()); } listFun.forEach(System.out :: println); } / * map中包含Function * * @return map */ private static Map<String, Function<Integer, Void>> mapIncludeFun() {
Map<String, Function<Integer, Void>> mapFun = new HashMap<>(); mapFun.put("a", test_a); mapFun.put("c", test_c); mapFun.put("d", test_c); return mapFun; } / * 包含Function Map的匿名函数 */ private static final Function<Integer, Void> test_a = (Integer num) -> {
System.out.println("测试函数a:" + num); return null; }; / * 包含Function Map的匿名函数 */ private static final Function<Integer, Void> test_c = (Integer num) -> {
System.out.println("测试函数c:" + num); return null; }; }
结果:1、 CSDN.MapToList$$Lambda$1/@6acbcfc0 CSDN.MapToList$$Lambda$2/@5f184fc6 CSDN.MapToList$$Lambda$2/@5f184fc6
2、Map
package CSDN; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; / * 2021/12/8 22:15 */ public class MapToList2 {
public static void main(String[] args) {
// 只包含简单的包装类的map转换成list,结果OK Map<Integer, String> simpleMap = simpleMap(); List<String> list = new ArrayList<>(); for (Map.Entry<Integer, String> map : simpleMap.entrySet()) {
list.add(map.getValue()); } list.forEach(System.out :: println); } / * map中不包含函数,只包含常见的包装类 * * @return map */ private static Map<Integer, String> simpleMap() {
Map<Integer, String> map = new HashMap<>(); map.put(3, "xiaoping"); map.put(9, "小铃铛"); return map; } }
结果:2、 xiaoping 小铃铛
3、map转换成list,使用stream
package CSDN; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; / * 2021/12/8 22:15 */ public class MapToList3 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>(); map.put(3, "liming"); map.put(12, "热忱"); List<Integer> list = new ArrayList(map.keySet()); list.forEach(System.out :: println); // 3 // 12 List<String> list1 = new ArrayList(map.values()); list1.forEach(System.out :: println); // liming // 热忱 List<Integer> list3 = map.keySet().stream().collect(Collectors.toList()); list3.forEach(System.out :: println); // 3 // 12 List<String> list4 = map.values().stream().collect(Collectors.toList()); list4.forEach(System.out :: println); // liming // 热忱 List<String> list5 = map.values().stream() .filter(x -> !"liming".equalsIgnoreCase(x)) .collect(Collectors.toList()); list5.forEach(System.out :: println); // 热忱 } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/214119.html原文链接:https://javaforall.net
