天天看點

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:我是新手,如有問題請多多賜教