Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filter Map<String,List<Object>> Using Java Streams

class Custom{
   String itemId,
   long createdTS
   //constructor
   public Custom(String itemId,long createdTS)
}

I have two maps which are

Map<String,Long> itemIDToFilterAfterTS;
Map<String,List<Custom>> itemIDToCustoms;

I want to filter 2nd map itemIDToCustoms values using 1st map itemIDToTimestampMap value for item using java streams.
eg.

itemIDToFilterAfterTS = new HashMap();
itemIDToFilterAfterTS.put("1",100);
itemIDToFilterAfterTS.put("2",200);
itemIDToFilterAfterTS.put("3",300);

itemIDToCustoms = new HashMap();
List<Custom> listToFilter = new ArrayList();
listToFilter.add(new Custom("1",50));
listToFilter.add(new Custom("1",90));
listToFilter.add(new Custom("1",120));
listToFilter.add(new Custom("1",130));
itemIDToCustoms.put("1",listToFilter)

Now I want to use java streams and want the filtered result map for which getKey("1") gives filtered list of Custom object which has createdTS > 100 (100 will be fetched from itemIDToFilterAfterTS.getKey("1"))

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Map<String,List<Custom>> filteredResult will be 
Map{
   "1" : List of (Custom("1",120),Custom("1",130))
}  

>Solution :

The stream syntax here is a bit too much

itemIDToCustoms = itemIDToCustoms.entrySet().stream().collect(Collectors.toMap(e -> e.getKey(),
            e -> e.getValue().stream().filter(val -> val.createdTS > itemIDToFilterAfterTS.get(e.getKey())).collect(Collectors.toList())));

More readable with a for loop + stream

for (Map.Entry<String, List<Custom>> e : itemIDToCustoms.entrySet()) {
    long limit = itemIDToFilterAfterTS.get(e.getKey());
    List<Custom> newValue = e.getValue().stream().filter(val -> val.createdTS > limit).collect(Collectors.toList());
    itemIDToCustoms.put(e.getKey(), newValue);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading