Home > OS >  Join a Map of String, List into a single List excluding the String
Join a Map of String, List into a single List excluding the String

Time:09-23

I have a Map<String, List<MyObject> myMap. How can I join all the List values into one List<MyObject>, excluding the String key?

I tried with this

List<MyObject> list = new ArrayList<MyObject>(myMap.values())

but this does not work with a collection.

Also thought of just iterating over the Maps and joining each list to a new list, but was hoping for a better way.

CodePudding user response:

here is a possible way with streams

map.values().stream().flatMap(Collection::stream).collect(Collectors.toList())

CodePudding user response:

I have a sample, it may helps you:

    public class App {
    
        public static void main(String[] args) {
            test();
        }
    
        private static void test() {
            Map<String, List<Test>> map = new HashMap<>();
            List<Test> test = new ArrayList<>();
            test.add(new Test(1, "AAA"));
            test.add(new Test(2, "BBB"));
            map.put("A", test);
            test = new ArrayList<>();
            test.add(new Test(3, "CCC"));
            test.add(new Test(4, "DDD"));
            map.put("B", test);
    
            System.out.println(map);
            List<Test> testList = new ArrayList<>();
            map.values().stream().forEach(tests -> tests.forEach(testData -> testList.add(testData)));
            System.out.println(testList);
        }
    }

class Test {
    private int id;
    private String name;

    //getter setters
}
  • Related