我有一个未排序的List
...假设它是ArrayList
,其中包含可以多次出现的字符串。我该如何首先对某个特定字符串的出现进行排序。其余条目可以按给定顺序保留。
例如。必须在顶部的某些字符串:“ JKL”
未排序:{ DEF, ABC, JKL, GHI, ABC, DEF, JKL, MNO, GHI, ABC, MNO, JKL }
排序:{ JKL, JKL, JKL, DEF, ABC, GHI, ABC, DEF, MNO, GHI, ABC, MNO }
有什么建议么? :)
最佳答案
使用Comparator
,但要确保比较器一致。
public void test() {
List<String> strs = Arrays.asList(new String[]{"DEF", "ABC", "JKL", "GHI", "ABC", "DEF", "JKL", "MNO", "GHI", "ABC", "MNO", "JKL"});
// All these are special and should appear at the front of the list.
Set<String> specials = new HashSet<>(Arrays.asList("ABC", "JKL"));
strs.sort((String o1, String o2) -> {
if (specials.contains(o1) == specials.contains(o2)) {
// Both special or both normal - just compare.
return o1.compareTo(o2);
} else if (specials.contains(o1)) {
// First is special!
return -1;
} else {
// Second is special.
return 1;
}
});
System.out.println(strs);
}