标签:override color turn 集合 code rabl 相关 style 多个
前言:很久没有写排序的方法,最近面试发现回答这类问题有点生疏,特此整理并复习一下相关知识。
public class Cell implements Comparable<Cell> { private int x; private int y; private int z; @Override public int compareTo(Cell o) { if (this.getX() != o.getX()) { // 若果X不相等,先对x排序 return this.getX() - o.getX(); } else if (this.getY() != o.getY()) { // 若x相等,然后通过Y排序 return this.getY() - o.getY(); } else { // 若x和y都相等,然后通过Z排序 return this.getZ() - o.getZ(); } } }
public static List<Cell> getCells() { List<Cell> arrayList = new ArrayList<>(); arrayList.add(new Cell(1, 1)); arrayList.add(new Cell(5, 2)); arrayList.add(new Cell(2, 2)); arrayList.add(new Cell(2, 5)); arrayList.add(new Cell(2, 3)); arrayList.add(new Cell(3, 3)); arrayList.add(new Cell(3, 2)); arrayList.add(new Cell(5, 12)); return arrayList; }
@Test public void test() { List<Cell> cells = TestCompare.getCells(); cells.sort(new Comparator<Cell>() { @Override public int compare(Cell o1, Cell o2) { if (o2.getX() == o1.getX()) { return o2.getY() - o1.getY(); } return o2.getX() - o1.getX(); } }); System.out.println(cells); }
@Test public void test2() { List<Cell> cells = TestCompare.getCells(); Collections.sort(cells); System.out.println(cells); }
@Test public void test3() { List<Cell> cells = TestCompare.getCells(); // 默认通过Cell的Comparable接口方法排序 List<Cell> collect = cells.stream().sorted().collect(Collectors.toList()); System.out.println(cells); }
@Test public void test4() { List<Cell> cells = TestCompare.getCells(); // 默认通过Cell的Comparable接口方法排序 List<Cell> collect = cells.stream().sorted(new Comparator<Cell>() { @Override public int compare(Cell o1, Cell o2) { if (o1.getX() != o2.getX()) { // 若果X不相等,先对x排序 return o1.getX() - o2.getX(); } else if (o1.getY() != o2.getY()) { // 若x相等,然后通过Y排序 return o1.getY() - o2.getY(); } else { // 若x和y都相等,然后通过Z排序 return o1.getZ() - o2.getZ(); } } }).collect(Collectors.toList()); System.out.println(collect); }
@Test public void test6() { List<Cell> cells = TestCompare.getCells(); List<Cell> collect = cells.stream().sorted(Comparator.comparing(c -> ((Cell) c).getX()).reversed()) .collect(Collectors.toList()); System.out.println(collect); }
@Test public void test7() { List<Cell> cells = TestCompare.getCells(); List<Cell> collect = cells.stream().sorted(Comparator.comparing(c -> ((Cell) c).getX(), (m1, m2) -> { return m1 - m2; }).reversed()).collect(Collectors.toList()); System.out.println(collect); }
@Test public void test5() { List<Cell> cells = TestCompare.getCells(); List<Cell> collect = cells.stream() .sorted(Comparator.comparing(Cell::getX).reversed().thenComparing(Cell::getY).thenComparing(Cell::getZ)) .collect(Collectors.toList()); System.out.println(collect); }
备注:如果是通过java1.8的stream()方法排序的,其不会影响原集合的顺序。
其他:利用if - else if - else 实现了对多个字段的排序
标签:override color turn 集合 code rabl 相关 style 多个
原文地址:https://www.cnblogs.com/jinliang374003909/p/13501667.html