简体   繁体   中英

Filter out maps from a list of maps based on values inside the map in Java groovy

I have a list of maps, with 3 key/values like this:

[
  [name: name1, date: Sat Oct 01 00: 00: 00 CEST 2021, doc: doc1],
  [name: name2, date: Sun Oct 14 00: 00: 00 CEST 2021, doc: doc1],
  [name: name2, date: Sat Oct 23 00: 00: 00 CEST 2021, doc: doc2],
//[name: name2, date: Sat Oct 15 00: 00: 00 CEST 2021, doc: doc2],
  [name: name2, date: Sat Oct 04 00: 00: 00 CEST 2021, doc: doc3],
  [name: name2, date: Sat Oct 11 00: 00: 00 CEST 2021, doc: doc4],
  [name: name3, date: Sat Oct 20 00: 00: 00 CEST 2021, doc: doc1],
  [name: name3, date: Sat Oct 03 00: 00: 00 CEST 2021, doc: doc2],
]

I need to find the most recent date for any given combination of name and doc, so for example if i have two docs of the same type for any given name i need to filter out all but the one with the most recent date.

In this case, I need to filter out the commented out line as another map with the same kind of name and doc exist with more recent date.

How can I accomplish this using a list of maps in Java Groovy?

You can groupBy your list over the values of the keys you want to group (eg name and doc ). Then collectMany over the resulting map: if there is only one item in the value , return it; otherwise reverse sort the items by the values of your sort-key (eg date ) and return the tail .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM