Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
58 views
in Technique[技术] by (71.8m points)

android - How to convert array list to map, matching keys to array value?

I have an array list of events, and I would like to convert them to a mutable map where one of the event values (date) is the key, and each key contains only events with that date. Below is an example of my original event list:

[Event(name="person 1", desc="hello", date="2021-01-05"), 
 Event(name="person 2", desc="hi", date="2021-01-05"), 
 Event(name="person 3", desc="hi", date="2021-01-08")]

By iterating though events and adding the key and events each time, I so far get this result:

{2021-01-05=[Event(name="person 1", desc="hello", date="2021-01-05"),
             Event(name="person 2", desc="hi", date="2021-01-05"), 
             Event(name="person 3", desc="hi", date="2021-01-08")],
 2021-01-08=[Event(name="person 1", desc="hello", date="2021-01-05"), 
             Event(name="person 2", desc="hi", date="2021-01-05"), 
             Event(name="person 3", desc="hi", date="2021-01-08")]}

The result below is what I need, but I am not sure how I would go about getting it. I've tried filtering the map and iterating again, but just cannot get the desired result. Any help would be appreciated.

{2021-01-05=[Event(name="person 1", desc="hello", date="2021-01-05"), 
             Event(name="person 2", desc="hi", date="2021-01-05")],
 2021-01-08=[Event(name="person 3", desc="hi", date="2021-01-08")]}
question from:https://stackoverflow.com/questions/65911235/how-to-convert-array-list-to-map-matching-keys-to-array-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can just use groupBy for this:

val map = events.groupBy(Event::date).toMutableMap()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...