1

I want to sort the following objects in the class. Each Element object has two field from and to. Here for e1 null is from v0 is to . I want to sort the elements as (null,v0),(v0,v1).....

public class Test7 {
    
    public static void main(String[] args) {
        
        Element e1 = new Element(null,"v0");
        Element e2 = new Element("v0","v1");
        Element e3 = new Element("v1","v2");        
        Element e4 = new Element("v2","v3");
        Element e5 = new Element("v3","v4");
        Element e6 = new Element("v4","v5");
        
        List<Element> elementList = new ArrayList();
        
        elementList.add(e3);

        elementList.add(e2);
        elementList.add(e1);
        elementList.add(e5);
        elementList.add(e6);

        elementList.add(e4);

    }
}

Can someone help me on this?

dariosicily
  • 1,062
  • 1
  • 4
  • 9
patnit
  • 11
  • 1

3 Answers3

3

you can do something like this:

Collections.sort(elementList);

and override the compareTo function inside the element. Assuming you want to compare the first string with the first one and second string with the second one in the element and your Element class looks like this:

public class Element implements Comparable<Element> {
    private String first;
    private String second;

    public Element(String first, String second) {
        this.first = first;
        this.second = second;
    }

    public String getFirst() {
        return first;
    }

    public String getSecond() {
        return second;
    }

    //you can add this compare to function
    @Override
    public int compareTo(Element other) {
        int compareFirst = compareStrings(first, other.getFirst());
        return compareFirst == 0 ? compareStrings(second, other.getSecond())
                                 : compareFirst;
    }

    private int compareStrings(String s1, String s2) {
        return s1 == null ? -1 : s1.compareTo(s2);
    }
}
Saheb
  • 1,190
  • 2
  • 12
  • 28
1

Your Element needs to implement Comarable Interface.

After which Collections.sort(elementList) will work.

@Saheb's answer above is using a Comparator for a Object without a Comparable Interface.

This beginner's book example goes into details about this topic.

Akin Okegbile
  • 969
  • 20
  • 33
0

Thanks for the answer. But my requirement is little bit different. I have a pojo like this class Element{

private String from;
private String to;


public Element(String from, String to) {
    super();
    this.from = from;
    this.to = to;
}

}

If i add the objects in a list i want to sort the objects like fromVersion->Toversion Example : obejcts created as (null,v0),(v1,v2),(v0,v1),(v2,v3)... So if we sort the list it becomes (null,v0),(v0,v1),(v1,v2),(v2,v3). Here to version of one object is the from version of the next object. We get a chain of objects. First objct from version is null. It means it has no parent object.

patnit
  • 11
  • 1