比较器内部排序的Stream方法

时间:2018-10-12 14:16:27

标签: java java-8

排序不正确,实际上根本不排序,我也不知道为什么

这是Comparator类:

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);
    }
}

这是主要部分

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);

2 个答案:

答案 0 :(得分:3)

如果您将其编写为:

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

如果您仍要使用比较器,请使用适当的方法使用它,例如Double::compare

答案 1 :(得分:1)

@khelwood提到了像(int)这样的转换为int的方法只是截断了小数部分。因此,最好将比较器更改为以下内容:

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;
  }
}

您可以使用调试器亲自检查代码以调查问题。