如何根据某些属性使用 RxJava2 对 ArrayList 进行分组?

How to group an ArrayList using RxJava2 based on some attribute?

我有一个 class Person,它具有 isChild 属性以及其他属性

class Person {
  boolean isChild;
  //Other attributes.
}

现在我有一个方法将 Person 的列表作为输入。我的输出也应该 return 一个列表,但是列表应该首先包含所有 Person 对象,其中 isChild 为真,然后是其他 Person 对象。在java中,我可以通过以下方式来实现。

public List<Person> returnListWithChildFirst(@NonNull List<Person> personList) {

    List<Person> childList = new ArrayList<>();
    List<Person> nonChildList = new ArrayList<>();

    for (Person person : personList) {
      if (person.isChild) {
        childList.add(person);
      } else {
        nonChildList.add(person);
      }
    }

    childList.addAll(nonChildList);
    return childList;
  }

在 RxJava2 中执行此操作的最佳方法是什么?

你可以这样做;

Observable.fromIterable(personList).sorted( (p1, p2) -> Boolean.compare(!p1.isChild(),!p2.isChild())).toList().blockingGet();

或 java 8

personList.stream().sorted(Comparator.comparing(Person::isChild).reversed()).collect(Collectors.toList());

只需使用 sorted 运算符:

public class RxJavaOrder {
    static class Person {
        public Person(boolean isChild, String name) {
            this.isChild = isChild;
            this.name = name;
        }

        public boolean isChild;
        public String name;

        @Override
        public String toString() {
            return "Person{" +
                    "isChild=" + isChild +
                    ", name='" + name + '\'' +
                    '}';
        }
    }

    public static void main(String[] args) {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person(true, "Tom"));
        personList.add(new Person(false, "Alie"));
        personList.add(new Person(false, "Ele"));
        personList.add(new Person(true, "Dale"));
        personList.add(new Person(false, "Cherry"));
        Observable.fromIterable(personList)
                .sorted((o1, o2) -> Boolean.compare(o2.isChild, o1.isChild))
                .toList()
                .subscribe(people -> {
                    people.forEach(System.out::println);
                });
    }
}