java对象嵌套内存分配,您如何使用Java Stream API根据存储在对象内部的信息将对象列表转换为嵌套映射?...

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值