2016-11-03 136 views
3

我有一個有3個變量(ID,版本,root_id)對象的列表如何使用Java流進行過濾

Eg : {(1, 3, 1001),(2,2,1001), (3,1,1001), (4,1,1002), (5,1,1003)}

我想保持具有相同root_id並具有最高的只有1對象版本號。

output : {(1, 3, 1001),(4,1,1002), (5,1,1003)}

如何申請名單上的Java流過濾器,以獲得所需的輸出。 請幫忙。我對使用過濾器有點困惑。

+3

沒有對象的定義,它具有法等無法幫助和你沒有向我們展示你的代碼和你困惑的地方。 – RealSkeptic

+1

另外,您沒有指定過濾條件。如果有多個具有相同根ID的對象,應該返回哪個對象? – Turing85

回答

3

rootId需要group並通過比較int值取maxversion

maxBy返回Optional數據,解開collectingAndThen用於

public static void main(String[] args) { 

    List<Data> objects = Arrays.asList(new Data(1, 3, 1001), new Data(2, 2, 1001), new Data(3, 1, 1001), 
      new Data(4, 1, 1002), new Data(5, 1, 1003)); 

    Map<Integer, Data> filtered = objects.stream().collect(Collectors.groupingBy(Data::getRootId, Collectors 
      .collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Data::getVersion)), Optional::get))); 

    System.out.println(filtered.values()); 
} 

static class Data { 
    int id; 
    int version; 
    int rootId; 

    //getter,setter & constructors 
    //toString 
} 

輸出的actaul數據

[Data [id=1, version=3, rootId=1001], Data [id=4, version=1, rootId=1002], Data [id=5, version=1, rootId=1003]] 
+0

感謝您的回答。 – shadab

+0

如何對來自同一個數據對象的附加列進行分組。我的意思是我引入了變量extensionId和repositoryId。我想對這三列進行分組。 (Collectors.maxBy(Comparator.comparingInt(Data :: getVersion)),Optional :: get(Collectors.groupingBy(Data::(getRootId,getExtensionId,getrepositoryId),收集器 .collectingAndThen )));' – shadab

+0

@shadab看看這個答案http://stackoverflow.com/a/28344135/3344829 – Saravana

0

您可以使用

.stream().collect(Collectors.groupingBy(Class::property)); 
0
.stream().filter((item) -> { 
    System.out.println(item); //this is element from your collection 
    boolean isOk = true; //change true to your conditional 
    return isOk; 
})