Home > Back-end >  Order by Key and merge values of a Map in java
Order by Key and merge values of a Map in java

Time:10-15

I have Map like this :

Map<Date, List<T>> data = new HashMap<Date, List<T>>();

In a for loop the data is added in this data map.

Now I have to merge the Value column from entire Map to a single List<T>. The merging should happen in the ascending order based on Key which is Data.

I have written a foreach loop like this :

List<T> newData = new List<T>(); 
Iterator<Map.Entry<Date , List<T>>> itr = data.entrySet().iterator();
         
while(itr.hasNext())
{
     Map.Entry<date, List<T>> entry = itr.next();
     newData.addAll(entry.getValue());
}

How can I make this order by Date (key) before adding to newData variable. Any help is highly appreciated.

CodePudding user response:

This is much easier with a stream pipeline, which would let you do both in one statement:

List<T> newData =  data.entrySet().stream()
        .sorted(Entry.comparingByKey())
        .map(Entry::getValue)
        .flatMap(List::stream)
        .collect(Collectors.toList());

Entry.comparingByKey() will give a comparator that uses keys (your date objects) to sort the stream.

Please note that your T objects will be included in the resulting list based only on the Date key they correspond to, there will not be any sorting of T values in the resulting list (unless they were already sorted in all smaller lists initially added to the map).

CodePudding user response:

// If you have an existing "data" hashmap. Otherwise, you can directly add into TreeMap.

TreeMap<Date, List<T>> yourSortedMap = new TreeMap<>(data);
Iterator<Map.Entry<Date , List<T>>> itr = yourSortedMap.entrySet().iterator();
         
while(itr.hasNext())
{
     Map.Entry<date, List<T>> entry = itr.next();
     newData.addAll(entry.getValue());
}
  • Related