Sonal Mishra
Sonal Mishra

Reputation: 1

Iterating over a List<Tuple> inside hashmap in java

I have stored a key-value pair in the hash map where key is a string ID and value is List of tuple .I need to fetch the data present in the list and insert into Database. What is the code logic to iterate over the List of tuple inside a map and get the data from the list?

Upvotes: 0

Views: 1151

Answers (2)

Suraj
Suraj

Reputation: 3137

You can get the values from map using map.values method or you can use Entry if you need to add some conditions based on keys.

Map<String, List<Tuple>> data = somemethod();

for(List<Tuple> tuples : data.values()) {
   //... some code
}

or

for(Map.Entry<String, List<Tuple>> entry : data.entrySet()) {
    String key = entry.getKey();
    List<Tuple> tuples = entry.getValue();
    // ... Some code
}

Upvotes: 0

Praveen
Praveen

Reputation: 9345

One of the ways is using Java 8 streams

map.values() // get all the list of tuples i.e. values
    .stream() // java 8 stream api
    .flatMap(listOfTuple -> listOfTuple.stream()) // flattening the list
    .forEach(tuple -> doWhatEverWithTuple(tuple)); // use individual tuple

Upvotes: 0

Related Questions