Issue
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"))
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);
}
Answered By - azro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.