I have a java collection of type Element and the idea is to sort it in ascending order. However, duplicated elements should be sorted by order of appearance. Let me explain a little bit better with some code:
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
}
}
In case this approach is not safe, I was considering to create a Wrapper class to do the sort. This wrapper class is something like:
public class ElementWrapperForSorting {
int value;
String position;
int positionOfAppearence;
}
That way, if the value is the same between elements, I can consider the field positionOfAppearence.