I have a list of objects List where SingleDay is
class SingleDay{
private Date date;
private String County;
// otherstuff
}
Im looking to convert this list into a Map>. 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!
解决方案
Do it as follows:
Map> 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 list = List.of(new SingleDay(LocalDate.now(), "X"),
new SingleDay(LocalDate.now().plusDays(1), "Y"), new SingleDay(LocalDate.now().plusDays(2), "Z"));
Map> 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.