我有一个类型为PARENT
的数组列表,并且列表中有子类型,我们称它们为CHILD1
和CHILD2
。
当前,我的列表看起来像[CHILD1 x, CHILD2 y, CHILD1, a]
,但我想要将CHILD1
元素放在第一位,即IE
[CHILD1 x, CHILD1 a, CHILD2, y]
我可以在流中应用按类型过滤器分组吗?
答案 0 :(得分:3)
Assuming that the number of subtypes is not too large and that you are not dealing with further subtypes of the children, you can simply make a list of subtypes with the order you want and sort by the position in the list:
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