EDIT: I have misunderstood the problem. This solution sorts on Field 1 followed by Field 2 followed by Field 3. This is not what OP is looking for.
I suspect that you have a Java object that contains these three fields. I'll assume that they can be accessed via getters. I will also assume that your objects are stored in a List of some kind.
You have not specified which version of Java you are using so I'll go with a Java 8 solution. This could be used with earlier version of Java but it would be more verbose.
List<MyObject> myObjects = Arrays.asList(new MyObject(1, 2, 3),
new MyObject(0, 1, 2),
new MyObject(1, 1, 1),
new MyObject(1, 1, 0),
new MyObject(1, 2, 1));
List<MyObject> sortedList = myObjects.stream()
.sorted(Comparator.comparing(MyObject::getField1)
.thenComparing(MyObject::getField2)
.thenComparing(MyObject::getField3))
.collect(Collectors.toList());
System.out.println(sortedList);
This program outputs
[0-1-2, 1-1-0, 1-1-1, 1-2-1, 1-2-3]
This solution uses Java 8 Stream API with the method sorted() which allows you to easily sort a Stream. The sort is achieved by using a Comparator which is a simple class that can determine which of two instances is "larger" than another.
Creating a Comparator that compares instances based on a field is very simple thanks to the Comparator.comparing() method. Comparing based on multiple fields is a simple process of chaining the returned Comparator using .thenComparing().
Java 8 method references are used to refer to field's getters.
Full code:
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class MyObject
{
private int field1;
private int field2;
private int field3;
public MyObject(int field1,
int field2,
int field3)
{
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
}
public int getField1()
{
return field1;
}
public int getField2()
{
return field2;
}
public int getField3()
{
return field3;
}
@Override
public String toString()
{
return field1 + "-" + field2 + "-" + field3;
}
public static void main(String[] args)
{
List<MyObject> myObjects = Arrays.asList(new MyObject(1, 2, 3),
new MyObject(0, 1, 2),
new MyObject(1, 1, 1),
new MyObject(1, 1, 0),
new MyObject(1, 2, 1));
List<MyObject> sortedList = myObjects.stream()
.sorted(Comparator.comparing(MyObject::getField1)
.thenComparing(MyObject::getField2)
.thenComparing(MyObject::getField3))
.collect(Collectors.toList());
System.out.println(sortedList);
}
}
Field 2is equal for two objects, and if they are, swap the values. Based onField 1The problem is, the sorting algorithm used by the library doesn't seem to compare everything so I have some values that are still unsorted.