[英]Java Stream - Create a Map of Sorted Duplicates
我有一個對象列表,其中一些對象共享相似的 ID,但是屬性的 rest 不同。 我知道如何按相似的 ID 對它們進行分組...
...
.stream()
.collect(groupingBy(obj -> obj.id, mapping(obj -> obj, toList())));
但是我想添加一層額外的邏輯。 我希望Map
中的每個List
都按兩個條件排序。
第一個條件,我想使用contains
檢查obj.specialId
是否存在於單獨的Set
中。 如果不是,那很好,但如果是,那么我希望 object 在Set
中排在第一位。 類似specialSet.contains(obj.specialId)
的東西。
第二個條件是我想讓它們按日期排序。 這些對象有一個名為 date 的屬性obj.date
。
條件並不重要,我最困惑的是如何保留Map
中值的順序。 一旦我知道如何做到這一點,添加我想要的條件應該很容易。
據我了解,您需要從使用 set 切換到使用 list 才能保持元素之間的順序。 然后你需要三個基本的代碼:
Thing::getId
類的分類器,這意味着使用 id 對它們進行分組。HashMap::new
。Collectors.collectingAndThen(...)
一個完整的例子:
public class Sandbox {
public static <T> List<T> doThingWithList( List<T> list) {
/**
* Do some fancy things on your grouped elements
* Such as sorting them
*/
return list;
}
public static void main(String[] args){
List<Thing> things = new ArrayList<>();
things.add(new Thing(1,"first", "first ever"));
things.add(new Thing(2,"second", "almost got first place"));
things.add(new Thing(2,"second","sharing the second place is better than finishing third"));
Map<Integer,List<Thing>> result = things.stream()
.collect(
Collectors.groupingBy(Thing::getId, HashMap::new,
Collectors.collectingAndThen(Collectors.toList(), Sandbox::doThingWithList))
);
System.out.println(result);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.