Reputation: 433
I have a list of objects List<SingleDay>
where SingleDay
is
class SingleDay{
private Date date;
private String County;
// otherstuff
}
Im looking to convert this list into a Map<Date, Map<String, SingleDay>>
. That is, I want a map from Date to a map of Counties back to the original object.
For example:
02/12/2020 : { "Rockbridge": {SingleDayObject}}
I have not been able to get anything to work and everything I found online if from a list of objects to a map, not a list of objects to a nested map.
Basically, I want to be able to quickly query the object that corresponds to the date and county.
Thanks!
Upvotes: 3
Views: 573
Reputation: 79085
Do it as follows:
Map<LocalDate, Map<String, SingleDay>> result = list.stream()
.collect(Collectors.toMap(SingleDay::getDate, v -> Map.of(v.getCounty(), v)));
Demo:
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class SingleDay {
private LocalDate date;
private String County;
public SingleDay(LocalDate date, String county) {
this.date = date;
County = county;
}
public LocalDate getDate() {
return date;
}
public String getCounty() {
return County;
}
@Override
public String toString() {
return "SingleDay [date=" + date + ", County=" + County + "]";
}
// otherstuff
}
public class Main {
public static void main(String[] args) {
List<SingleDay> list = List.of(new SingleDay(LocalDate.now(), "X"),
new SingleDay(LocalDate.now().plusDays(1), "Y"), new SingleDay(LocalDate.now().plusDays(2), "Z"));
Map<LocalDate, Map<String, SingleDay>> result = list.stream()
.collect(Collectors.toMap(SingleDay::getDate, v -> Map.of(v.getCounty(), v)));
// Display
result.forEach((k, v) -> System.out.println("Key: " + k + ", Value: " + v));
}
}
Output:
Key: 2020-05-27, Value: {Z=SingleDay [date=2020-05-27, County=Z]}
Key: 2020-05-26, Value: {Y=SingleDay [date=2020-05-26, County=Y]}
Key: 2020-05-25, Value: {X=SingleDay [date=2020-05-25, County=X]}
Note: I've used LocalDate
instead of outdated java.util.Date
. I highly recommend you use java.time API instead of broken java.util.Date
. Check this to learn more about it.
Upvotes: 6
Reputation: 1030
A slightly more readable data structure would be making a Map<SingleDay, SingleDay>
. Might seem redundant but that will allow you to easily find your objects.
Map<SingleDay, SingleDay> myMap = new HashMap();
list.forEach(day -> myMap.put(day, day));
Then to get one you can just do
SingleDay day = mMap.get(myDay);
Very important to not forget to override the equals()
method of SingleDay
, based on what you consider as equal.
Upvotes: -1