Asmaa Salman
Asmaa Salman

Reputation: 67

Convert from map to arraylist

I tried to convert a Map<String,ArrayList<Object>> to ArrayList<Object> using this code:

Collection<ArrayList<Object>> coll = map().values();
List list = new ArrayList(coll);
ArrayList<Object> arrayList = new ArrayList<>(list.size());
arrayList.addAll(list);

However, the arraylist I got still groups objects by key still as collection.

How can I convert to ArrayList of separate Objects?

Upvotes: 1

Views: 76

Answers (3)

Pradeep
Pradeep

Reputation: 12675

same result can be achieved by using following traditional approach as well -

Map<String, ArrayList<Object>> map = new HashMap<>();
        ArrayList<Object> objects1 = new ArrayList<>();
        objects1.add("data1");
        objects1.add("data2");
        objects1.add("data3");
        map.put("key1", objects1);
        ArrayList<Object> objects2 = new ArrayList<>();
        objects2.add("data1");
        objects2.add("data2");
        objects2.add("data3");
        map.put("key2", objects2);
        Collection<ArrayList<Object>> collections = map.values();
        List<Object> list = new ArrayList<>();
        for(ArrayList<Object> collection : collections) {
            for(Object obj : collection) {
                list.add(obj);
            }
        }
        System.out.println(list);

It will print the output as :

[data1, data2, data3, data1, data2, data3]

Upvotes: 0

Ousmane D.
Ousmane D.

Reputation: 56423

A non stream version would be:

List<Object> accumulator = new ArrayList<>();
for(ArrayList<Object> a : map.values())
      accumulator.addAll(a);

Upvotes: 0

Eran
Eran

Reputation: 393781

You can use Java 8 Streams:

List<Object> list =  map.values().stream()
                         .flatMap(ArrayList::stream)
                         .collect(Collectors.toList());

Without Streams, you'll have to iterate over the elements of your first List and call arrayList.addAll() for each of them separately.

Upvotes: 2

Related Questions