简体   繁体   English

在Java8流中使用分组方式

[英]Use of grouping by in java8 streams

I have a List of Event objects i want to transform to JSON. 我有一个想要转换为JSON的事件对象列表。

An event is defined as below : 事件定义如下:

public class Event {

    private final String name;
    private final Date date;

    public Event(String name, Date date) {
        this.name = name;
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public Date getDate() {
        return date;
    }
}

the code below : 下面的代码:

List<Event> events = ...;
        SimpleDateFormat dayFormatter=new SimpleDateFormat("dd/MM/yyyy");
        Map<String,List<JsonNode>> result = events.stream().map(event -> {
            ObjectNode jsonMatch = jsonNodeFactory.objectNode();
            jsonMatch.put("name",event.getName());
            jsonMatch.put("day",dayFormatter.format(event.getDate()));
            return jsonMatch;
        }).collect(Collectors.groupingBy(item -> item.get("day").asText(),
                Collectors.toList()));

creates me a json that i want, which looks like this : 为我创建一个我想要的json,看起来像这样:

{
    "10/03/2014": [{name:"event1",day:"10/03/2014"},{name:"event2",day:"10/03/2014"}]
}

but to me, the day attribute in each event node is a redundant information that i want to bypass, in order to obtain this json : 但对我来说,每个事件节点中的day属性是我要绕过的冗余信息,以便获取此json:

{
        "10/03/2014": [{name:"event1"},{name:"event2"}]
    }

but if i dont put it in the object, i cant do a groupingby on it. 但是,如果我不将其放在对象中,则无法对其进行分组。 Is there any workaround to make it happen? 有什么解决方法可以实现?

Don't do the mapping step before the collect operation, do it only for the values of the groups. 不要在collect操作之前执行映射步骤,而仅对组的值执行。

SimpleDateFormat dayFormatter=new SimpleDateFormat("dd/MM/yyyy");
Map<String,List<JsonNode>> result = events.stream()
    .collect(Collectors.groupingBy(event -> dayFormatter.format(event.getDate()),
        Collectors.mapping(event -> {
            ObjectNode jsonMatch = jsonNodeFactory.objectNode();
            jsonMatch.put("name", event.getName());
            return jsonMatch;
        }, Collectors.toList())));

You can use Collectors.toMap() method: 您可以使用Collectors.toMap()方法:

Map<String,List<JsonNode>> result = events.stream()
    .map(event -> {
        ObjectNode jsonMatch = jsonNodeFactory.objectNode();
        jsonMatch.put("name",event.getName());
        jsonMatch.put("day",dayFormatter.format(event.getDate()));
        return jsonMatch;
    })  
    .collect(Collectors.toMap(
        item -> item.get("day").asText(),
        item -> new ArrayList<>(Arrays.asList(item.get("name"))),
        (i1, i2) -> {
            i1.addAll(i2);
            return i1;
        }
    ));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM