我有一个 Element 类型的 java 集合,想法是按升序对其进行排序。但是,重复的元素应按出现顺序排序。让我用一些代码更好地解释一下:
public class Sorting {
// Element class
public static class Element {
int value;
String position;
}
// Comparator class
public static class ElementComparator implements Comparator<Element> {
@Override
public int compare(Element e1, Element e2) {
if (e1.value != e2.value) return e1.value - e2.value;
return 1; // Elements have same value, so with this condition
// am I guaranteeing that duplicated elements are
// sorted by order of appearance ?
// I have been testing with this approach and it has worked fine
// but I am not sure how the sort could behave
// for other scenarios, eg, multithread environment
// I would like to know if this is a safe approach
}
@Override
public String toString() {
return "Element{" + "number=" + number + ", position=" + position + '}';
}
}
// Main
public static void main(String[] args) {
List<Element> elements = new LinkedList<>();
elements.add(new Element(3, "first 3"));
elements.add(new Element(2, "first 2"));
elements.add(new Element(2, "second 2"));
elements.add(new Element(1, "first 1"));
elements.add(new Element(1, "second 1"));
elements.sort(new ElementComparator());
for (Element e : elements) {
System.out.println(e);
}
// It will print:
// Element{number=1, position=first 1}
// Element{number=1, position=second 1}
// Element{number=2, position=first 2}
// Element{number=2, position=second 2}
// Element{number=3, position=first 3}
// Notice that duplicated elements are sorted by order of appearance
}
}
如果这种方法不安全,我正在考虑创建一个 Wrapper 类来进行排序。这个包装类类似于:
public class ElementWrapperForSorting {
int value;
String position;
int positionOfAppearence;
}
这样,如果元素之间的值相同,我可以考虑字段 positionOfAppearence。
最佳答案
你不需要包装器。 List.sort
是稳定的,所以相等的元素不会被重新排序。见 javadoc .
关于Java 对具有重复元素的集合进行排序。如果重复,按出现顺序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61295362/