Jac*_*all 3 java date java-stream
我有对象的列表List<SingleDay>,其中SingleDay是
class SingleDay{
private Date date;
private String County;
// otherstuff
}
Run Code Online (Sandbox Code Playgroud)
我希望将此列表转换为Map<Date, Map<String, SingleDay>>. 也就是说,我想要一张从 Date 到 Counties 的地图回到原始对象的地图。
例如:
02/12/2020 : { "Rockbridge": {SingleDayObject}}
如果从对象列表到地图,而不是从对象列表到嵌套地图,我无法让任何工作以及我在网上找到的所有内容。
基本上,我希望能够快速查询与日期和县对应的对象。
谢谢!
请按以下步骤操作:
Map<LocalDate, Map<String, SingleDay>> result = list.stream()
.collect(Collectors.toMap(SingleDay::getDate, v -> Map.of(v.getCounty(), v)));
Run Code Online (Sandbox Code Playgroud)
演示:
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));
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
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]}
Run Code Online (Sandbox Code Playgroud)
注意:我使用了LocalDate而不是过时的java.util.Date. 我强烈建议您使用java.time API 而不是Brokenjava.util.Date。检查这个以了解更多信息。