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

时间:2018-07-25 03:39:28

标签: java-8

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

当前,我的列表看起来像[CHILD1 x, CHILD2 y, CHILD1, a],但我想要CHILD1元素放在第一位,即IE [CHILD1 x, CHILD1 a, CHILD2, y]

我可以在流中应用按类型过滤器分组吗?

1 个答案:

答案 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