2016-07-24 33 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()); 
相關問題