您如何使用Java Stream API根据存储在对象内部的信息将对象列表转换为嵌套映射? [英] How do you use java stream api to convert list of objects into a nested map based on information stored inside object?

查看:86
本文介绍了您如何使用Java Stream API根据存储在对象内部的信息将对象列表转换为嵌套映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象List<SingleDay>的列表,其中SingleDay

I have a list of objects List<SingleDay> where SingleDay is

class SingleDay{ 
      private Date date;
      private String County;

   // otherstuff
}

我希望将此列表转换为Map<Date, Map<String, SingleDay>>.也就是说,我希望从Date到Counties的地图都回到原始对象.

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.

例如:
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.

谢谢!

推荐答案

执行以下操作:

Map<LocalDate, Map<String, SingleDay>> result = list.stream()
                .collect(Collectors.toMap(SingleDay::getDate, v -> Map.of(v.getCounty(), v)));

演示:

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));
    }
}

输出:

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]}

注意:我使用的是LocalDate而不是过时的java.util.Date.我强烈建议您使用,以了解更多信息.

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.

这篇关于您如何使用Java Stream API根据存储在对象内部的信息将对象列表转换为嵌套映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆