天天看点

java 重写compare 排序集合A 将集合B所包含的内容放在前面

集合A  ["1", "2", "3", "4", "5", "6"]

集合B  [ "3","6"]

现在需要 排序集合A将集合B所包含的内容放在前面

通过重写compare实现

compare返回值:

正数:o1排在o2后面

零:顺序不变

负数:o1排在o2前面

List<String> collectA = Lists.newArrayList("1", "2", "3", "4", "5", "6");
    List<String> collectB = Lists.newArrayList("3", "6");
    List<String> collect = collectA.stream().sorted(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return collectB.contains(o1) ? -1 : 0;
        }
    }).collect(Collectors.toList());
    System.out.println(collect);
           
输出结果 [6, 3, 1, 2, 4, 5]

 ps:我是新手,如有问题请多多赐教