For Java 8, you can convert the Map into a stream, process it and returns it back as a List

示例代码

package com.test;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ConvertMapToList {

    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(10, "apple");
        map.put(20, "orange");
        map.put(30, "banana");
        map.put(40, "watermelon");
        map.put(50, "dragonfruit");

        System.out.println("\n1. Export Map Key to List...");

        List<Integer> result = map.keySet().stream()
                .collect(Collectors.toList());

        result.forEach(System.out::println);

        System.out.println("\n2. Export Map Value to List...");

        List<String> result2 = map.values().stream()
                .collect(Collectors.toList());

        result2.forEach(System.out::println);

        System.out.println("\n3. Export Map Value to List..., say no to banana");
        List<String> result3 = map.keySet().stream()
                .filter(x -> !"banana".equalsIgnoreCase(x))
                .collect(Collectors.toList());

        result3.forEach(System.out::println);

    }

}

输出

1. Export Map Key to List...
50
20
40
10
30

2. Export Map Value to List...
dragonfruit
orange
watermelon
apple
banana

3. Export Map Value to List..., say no to banana
dragonfruit
orange
watermelon
apple

标签: Java 8 – Map转化成List


阿里云优惠主机

添加新评论

免责声明
本博客部分内容来自于互联网,不代表作者的观点和立场,如若侵犯到您的权益,请联系[email protected]。我们会在24小时内进行删除。