Java 8过滤以根据列表中的类型排序数据



我有一个类型为PARENT的数组列表和列表中的子类型,我们称它们为CHILD1CHILD2

目前,我的列表看起来像[CHILD1 x, CHILD2 y, CHILD1, a],但我希望将CHILD1元素放在第一位,IE[CHILD1 x, CHILD1 a, CHILD2, y]

是否有可以在流中应用的按类型分组的筛选器?

假设子类型的数量不太多,并且您没有处理子类型的其他子类型,您可以简单地按照您想要的顺序列出子类型列表,并按列表中的位置排序:

List<Class<? extends Parent>> order = Arrays.asList(Child1.class, Child2.class, Child3.class, ...);
Comparator<Parent> bySubtype = Comparator.comparing(p -> order.indexOf(p.getClass()));
list.sort(bySubtype);  // sort in place
List<Parent> sorted = list.stream()
.sorted(bySubtype)
.collect(Collectors.toList());   // sort into a new list with a stream

最新更新