简体   繁体   中英

Comparator inside sorted Stream method

It doesn't sort properly, actually it doesn't sort at all and I don't know why

this is Comparator class:

public class Komparator implements Comparator<BoardGame> {

    @Override
    public int compare(BoardGame o1, BoardGame o2) {
        System.out.println(o1.rating+"-"+o2.rating);
        return (int) (o2.rating-o1.rating);
    }
}

this is main part

List<BoardGame> games = Arrays.asList(
                new BoardGame("Terraforming Mars", 8.38, new BigDecimal("123.49"), 1, 5),
                new BoardGame("Codenames", 7.82, new BigDecimal("64.95"), 2, 8),
                new BoardGame("Puerto Rico", 8.07, new BigDecimal("149.99"), 2, 5),
                new BoardGame("Terra Mystica", 8.26, new BigDecimal("252.99"), 2, 5),
                new BoardGame("Scythe", 8.3, new BigDecimal("314.95"), 1, 5),
                new BoardGame("Power Grid", 7.92, new BigDecimal("145"), 2, 6),
                new BoardGame("7 Wonders Duel", 8.15, new BigDecimal("109.95"), 2, 2),
                new BoardGame("Dominion: Intrigue", 7.77, new BigDecimal("159.95"), 2, 4),
                new BoardGame("Patchwork", 7.77, new BigDecimal("75"), 2, 2),
                new BoardGame("The Castles of Burgundy", 8.12, new BigDecimal("129.95"), 2, 4)
        );

games.stream().filter(g->g.name.contains("a")).
                sorted(new Komparator()).
                map(g->g.name).forEach(System.out::println);

It would be a lot easier (and less error prone) if your would write it as:

games.stream()
     .filter(g->g.name.contains("a"))
     .sorted(Comparator.comparingDouble(BoardGame::getRating))
     ....

If you still want to use your comparator, use it with a proper method, like Double::compare

As @khelwood mentioned conversion to int like (int) just truncates decimal part. So you'd better change comparator to the following:

public class Komparator implements Comparator<BoardGame> {

  @Override
  public int compare(BoardGame o1, BoardGame o2) {
    System.out.println(o1.rating+"-"+o2.rating);
    if (o2.rating > o1.rating) return 1;
    if (o2.rating == o1.rating) return 0;
    return -1;
  }
}

And you can use debugger to go through your code to investigate an issue yourself.

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