sForSujit
sForSujit

Reputation: 985

Retrieving values from nested collection

I have Map inside List as below :

List<Map<String, Object>> migrationMap = new LinkedList<Map<String, Object>>();

I want to display the values of list "migrationMap".

Could anyone help me out

Upvotes: 2

Views: 274

Answers (1)

bleistift2
bleistift2

Reputation: 525

Every map implements the values() method, which returns a collection of all values contained in the map, see JavaDoc. Knowing this, you can iterate over the list of maps and then over the values returned by values() to print these:

List<Map<String, Object>> migrationMap = new LinkedList<Map<String, Object>>();
for(Map m: migrationMap){ // For every element in the list
    for(Object v: m.values()){ // For every value that is stored in this list element’s map
        System.out.println(v.toString()); // Print that value
    }
}

If, for instance, you want to perform a test on the values to be printed, or otherwise manipulate them, you can use the keySet method to get a collection of all keys in the map.

for(Map m: migrationMap){ // For every element in the list
    Set<String> keys = m.keySet(); // Get a set of all keys in the map
    for(key: keys){ // For every key in said set
        Object value = m.get(key); // Retrieve the object referenced by this key
        System.out.println(m.get(key)); // Print it
    }
}

Upvotes: 3

Related Questions