2016-07-24 38 views
-3

我想通过Java8的流API构造一个自定义类实例。Java8 Stream API:将列表分组到一个自定义类

public class Foo { 
    Group group; 
    // other properties 

    public Group getGroup() { return this.group; } 

    public enum Group { /* ... */ }; 
} 

public class FooModel { 
    private Foo.Group group; 
    private List<Foo> foos; 

    // Getter/Setter 
} 

... 

List<Foo> inputList = getFromSomewhere(); 

List<FooModel> outputList = inputList 
    .stream() 
    .collect(Collectors.groupingBy(Foo::getGroup, 
            ???)); 

但我不知道Collector downstream必须如何。 我是否必须自己实现Collector(不这么认为),还是可以通过Collectors.调用的组合来实现?

+0

你为什么要分组?你想要什么结果?你能发表一个输入/输出的例子吗? – Tunaki

+0

我真的没有重读三次后得到的问题。你介意更具体吗? –

回答

2

您正在寻找这样的事情:

List<FooModel> outputList = inputList 
    .stream() 
    .collect(Collectors.groupingBy(Foo::getGroup))// create Map<Foo.Group,List<Foo>> 
.entrySet().stream() // go through entry set to create FooModel 
.map(
entry-> new FooModel (
entry.getKey(), 
entry.getValue() 
) 
).collect(Collectors.toList()); 
相关问题