简体   繁体   中英

Sorting ObservableList understanding Comparator and Predicate

I have an ObservableList<Auftrag> which contains some data.

private ObservableList<Auftrag> data = FXCollections.observableArrayList();
// add some test data
data.add(new Auftrag("AB1", "Car 1",1));
data.add(new Auftrag("AB1", "Car 2",22));
data.add(new Auftrag("AB1", "Car 3",2));
data.add(new Auftrag("AB2", "Fruit A",33));
data.add(new Auftrag("AB2", "Fruit B",45));   
data.add(new Auftrag("AB3", "Music 1",101));
data.add(new Auftrag("AB3", "Music 2",102));
data.add(new Auftrag("AB3", "Music 3",103));

Now I'd like to return an ordered list which is ordered by the third data parameter (int) ASC . I tried by using the SortedList by setting a comparator but without luck.

I'm honest the documentation about Sorting and Filtering is a bit "filtered" ;) I like to understand the Comparator and Predicate use...for beginners...

What I tried so far is to put the ObservableList into a sortedList and played with the comparator. getDaysTillDelivery() is a function in Auftrag model which returns the int value.

SortedList<Auftrag> sorted = data.sorted();
sorted.setComparator(new Comparator<Auftrag>() {
   @Override
   public int compare(Auftrag arg0, Auftrag arg1) {
      return arg0.getDaysTillDelivery() > arg1.getDaysTillDelivery() ? arg0.getDaysTillDelivery(): arg1.getDaysTillDelivery();
   }
});

By using predicate I had no clue using existing examples found by google .

Any help would be great thx.

sorted.setComparator(new Comparator<Auftrag>() {
   @Override
   public int compare(Auftrag arg0, Auftrag arg1) {
      return arg0.getDaysTillDelivery() > arg1.getDaysTillDelivery() ? arg0.getDaysTillDelivery(): arg1.getDaysTillDelivery();
   }
});

That won't work.

And what is unclear about the documentation of Comparator ? Quoting the javadoc itself about the compare() method reads (emphasis mine):

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second .

That is clear enough to me.

Your comparator should read (note: Java 8 code)

sorted.setComparator(Comparator.comparing(Auftrag::getDaysTillDelivery));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM