Android sort array - java
i have a string array consisting of a name and a score. I want to sort that array by score. Problem is, considering it's a string array, the scores are strings which results in 13,16,2,5,6 and not 2,5,6,13,16. I am using this code:
int spaceIndex;
String[][] scoreboard;
String[] playername;
String[] score;
int sbsize;
array1.add("Thomas" + ":" + 5);
array1.add("Blueb" + ":" + 6);
array1.add("James" + ":" + 16);
array1.add("Hleb" + ":" + 13);
array1.add("Sabbat" + ":" + 2);
sbsize = array1.size();
scoreboard = new String[sbsize][2];
playername = new String[sbsize];
score = new String[sbsize];
pos2 = new int[sbsize];
for (int i=0; i<array1.size(); i++)
{
spaceIndex = array1.get(i).indexOf(':');
scoreboard[i][0] = array1.get(i).substring(0, spaceIndex);
scoreboard[i][1] = array1.get(i).substring(spaceIndex+1, array1.get(i).length());
}
Arrays.sort(scoreboard, new Comparator<String[]>() {
#Override
public int compare(String[] entry1, String[] entry2) {
String time1 = entry1[1];
String time2 = entry2[1];
return time1.compareTo(time2);
}
});
What is the solution?
Cast them to int. As I recall, something like...
Arrays.sort(scoreboard, new Comparator<String[]>() {
#Override
public int compare(String[] entry1, String[] entry2) {
Integer time1 = Integer.valueOf(entry1[1]);
Integer time2 = Integer.valueOf(entry2[1]);
return time1.compareTo(time2);
}
});
Also you can make simple value object class for easier manipulations. Like...
class Player
{
public String name;
public int score;
}
And after that you can make
Player[] scoreboard = ...
Arrays.sort(scoreboard, new Comparator<Player>() {
#Override
public int compare(Player player1, Player player2) {
if(player1.score > player2.score) return 1;
else if(player1.score < player2.score) return -1;
else return 0;
}
});
Edit:
I recommend you to understand the basic OOP principles, this will help you a lot in the beginning.
Edit 2: Java 8 (with functional interface and a lambda):
Arrays.sort(scoreboard, (player1, player2) -> {
Integer time1 = Integer.valueOf(player1[1]);
Integer time2 = Integer.valueOf(player2[1]);
return time1.compareTo(time2);
});
This is the easy way of Sorting String Array:
Arrays.sort(mystringarray);
Use
java.util.Arrays.sort(yourArray, new Comparator<String>() {
#Override
public int compare(String object1, String object2) {
return Integer.valueOf(object1).compareTo(Integer.valueOf(object2));
}
});
Comparator will compare your strings as integers.
ArrayList<String> names= new ArrayList<String>();
names.add("sathish");
names.add("Ravi");
names.add("Praksh");
names.add("pavithara");
names.add("Duraga");
names.add("uma");
names.add("Upendar");
System.out.println("Before sorting");
System.out.println("Names : "+names);
Collections.sort(names, new Comparator<String>() {
#Override
public int compare(String lhs, String rhs) {
return lhs.compareToIgnoreCase(rhs);//Ascending order.
//return (lhs.compareToIgnoreCase(rhs)*(-1));//Descending order.
}
});
System.out.println("After sorting");
System.out.println("Names : "+names);
output:
Before sorting
Names : [sathish, Ravi, Praksh, pavithara, Duraga, uma, Upendar]
After sorting
Names : [Duraga, pavithara, Praksh, Ravi, sathish, uma, Upendar]
If possible use better data structure for your problem, use HashMap, with name to score mapping and , sort the hashmap with values.
If you want to go with arraylist as described by you, before sorting, convert them into integer and sort, then back to string.
You would probably be better off storing the names + results in objects, then storing those in an ArrayList. You can then sort very easily using a custom comparator, see the link for a simple example: http://www.javabeat.net/tips/20-sorting-custom-types-in-java.html
Score should be a class like
public class HighScore Comparable<HighScore>
{
private String name;
private int score;
public Score( String name, int score )
{
this.name = name;
this.score = score;
}//cons
//getters
public String getName() {
return name;
}//met
public int getScore() {
return score;
}//met
#Override
public int compareTo( HighScrore b )
{
int diffScore = score - b.score;
if( diffScore != 0)
return diffScore;
else
return name.compareTo( b.name );
}//met
public boolean equals( Object o )
{
if( !(o instanceof HighScore))
return false;
HighScore b = (HighScore) o;
return score == b.score && name.equals( b.name );
}//met
}//class
Then you can build score objects,
String[] stringParts[];
List<HighScore> listHighScore = new ArrayList<HighScore>();
for (int i=0; i<array1.size(); i++)
{
stringParts = array1.get(i).split(':');
listHighScore.add( new HighScore( stringParts[ 0 ], Integer.parseInt( stringParts[ 1 ])) );
}//for
put them in a List and sort them through
Collections.sort( list );
Regards,
Stéphane
You can use ArrayList instead of Array.
Please check this link
Related
How to add/append new rows from Array1[][] that do not exist in Array2[][] to Array2[][] in Java?
I came across a problem where one needs to check for rows in Array1 that are not in Array2 and append it at the end of Array2 in Java. The rows that are common with regard to the first column i.e. name can be skipped. In the below example, the rows in firstarray with "Nick" and "Bruce" should be appended at the end of secondarray. I have edited the arrays again slightly to get more clarity. String firstarray[][] = { {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}, {"Nick","09-06-1974","History","Johanesburg"}, {"Bruce","13-08-1975","Philosophy","Seattle"}}; String secondarray[][] = { {"Adam","01-Dec-1980","Commerce","New York"}, {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}}; The solution should be like: secondarray[][]: {"Adam","01-Dec-1980","Commerce","New York"}, {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}, {"Nick","09-06-1974","History","Johanesburg"}, {"Bruce","13-08-1975","Philosophy","Seattle"}}
Collect the names of the second array to a set, iterate over your first array and filter out those elements which are in the set and collect the result in a third array (or any other collection). Append this collection to your second array. public static void main(String[] args){ String firstarray[][] = { {"Adam","01-Dec-1980","Commerce","Kansas"}, {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}, {"Nick","09-06-1974","History","Johanesburg"}, {"Bruce","13-08-1975","Philosophy","Seattle"}}; String secondarray[][] = { {"Adam","01-Dec-1980","Commerce","Kansas"}, {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}, {"Sujay Muramalla","08-Jan-1985","Arts","London"}}; //collect names of second array to set Set<String> secondSet = Arrays.stream(secondarray).map(e -> e[0]).collect(Collectors.toSet()); //stream over your first array and keep only those which are not in the above set String[][] third = Arrays.stream(firstarray) .filter(e -> !secondSet.contains(e[0])) .toArray(String[][]::new); //stream over second and delta (third array) and collect to a result array String[][] result = Stream.concat(Arrays.stream(secondarray), Arrays.stream(third)) .toArray(String[][]::new); //output Arrays.stream(result).forEach(e ->{ System.out.println(Arrays.toString(e)); }); }
You should not be using arrays for this. Much better to use libraries already doing the job. Even if the data you receive is already that way, you can converted first to a Map<String, Person> it will be more efficient, and readable code. With arrays or many solutions not using some hashing system, you end up with exponential complexity O(n2), so not efficient. Convert at least secondarray Map<String, Person> secondMap = new HashMap(); for(String [] row : secondarray){ secondMap.put(row[0], new Person(row[0], row[1], row[2], row[3])); } Then put in the map if not already there for(String[] row : firstarray){ if(!secondMap.containsKey(row[0])){ secondMap.put(row[0], new Person(row[0], row[1], row[2], row[3])); } } Where Person class could be simply defined as private static class Person{ public Person(String name, String birth, String area, String city){ this.name = name; this.birth = birth; this.area = area; this.city = city; } String name; String birth; String area; String city; }
if you want check more than the first element of the array you can use nopens solution and replace e[0] with Arrays.toString(e). A cleaner way if this is possible for you, is to use a list with a object and use a id for checking equals or override the hashcode function of the customer object. You can also check for name and birth like that: class Customer { private String name; private String birth; private String type; private String location; public Customer(String name, String birth, String type, String location) { this.name = name; this.birth = birth; this.type = type; this.location = location; } #Override public String toString() { return "Customer [name=" + name + ", birth=" + birth + ", type=" + type + ", location=" + location + "]"; } } List<Customer> firstList = new ArrayList<Customer>(); firstList.add(new Customer("Adam", "01-Dec-1980", "Commerce", "Kansas")); firstList.add(new Customer("John", "04-Feb-1982", "Economics", "Leeds")); firstList.add(new Customer("Mathias", "08-Jan-1985", "Arts", "London")); firstList.add(new Customer("Nick", "09-06-1974", "History", "Johanesburg")); firstList.add(new Customer("Bruce", "13-08-1975", "Philosophy", "Seattle")); List<Customer> secondList = new ArrayList<Customer>(); secondList.add(new Customer("Adam", "01-Dec-1980", "Commerce", "Kansas")); secondList.add(new Customer("John", "04-Feb-1982", "Economics", "Leeds")); secondList.add(new Customer("Mathias", "08-Jan-1985", "Arts", "London")); for (Customer customer : firstList) { if (containsNameAndBirth(secondList, customer) == false) { secondList.add(customer); } } for (Customer customer : secondList) { System.out.println(customer); } } public static boolean containsNameAndBirth(final List<Customer> list, final Customer customer) { return list.stream().filter(o -> o.name.equals(customer.name) && o.birth.equals(customer.birth)).findFirst() .isPresent(); }
EDIT 1 - Using Custom Class I suggest you to always use List over Array. import java.time.*; import java.util.*; import java.util.stream.Collectors; public class Main { static class Person { public String name; public String birthDate; public String field; public String city; public static Person fromArray(String[] data) { Person p = new Person(); if (data.length == 4) { p.name = data[0]; p.birthDate = data[1]; p.field = data[2]; p.city = data[3]; } else { // Handle me } return p; } #Override public String toString() { return new StringBuilder("[").append(name) .append(",").append(birthDate) .append("] learns ").append(field) .append(" at ").append(city).toString(); } } public static void main(String[] args) { String firstArray[][] = { {"Adam","01-Dec-1980","Commerce","Kansas"}, {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}, {"Nick","09-06-1974","History","Johanesburg"}, {"Bruce","13-08-1975","Philosophy","Seattle"}}; String secondArray[][] = { {"Adam","01-Dec-1980","Commerce","Kansas"}, {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}}; List<Person> finalList = getFinalList(firstArray, secondArray); // Display System.out.println(finalList); } public static List<Person> getFinalList(String[][] arr1, String[][] arr2) { // First cast to Lists of persons List<Person> firstList = Arrays.asList(arr1).stream().map(Person::fromArray).collect(Collectors.toList()); List<Person> secondList = Arrays.asList(arr2).stream().map(Person::fromArray).collect(Collectors.toList()); // Get names in secondList Set<String> existingNames = secondList.stream().map(p -> p.name).collect(Collectors.toSet()); System.out.println("Names: "+ existingNames); firstList.forEach(person -> { if (! existingNames.contains(person.name)) { secondList.add(person); } }); return secondList; } }
I upvoted nopens solutions cause it is nice one Here another that uses maps and makes use of a logic of skipping common keys using removeAll on the keySet of the map, which was a functional method existing befor Java turned "more" functional static public <T> Map<T,T[]> arrayToMap(T[][] array, int i) { return Arrays.stream(array).collect(Collectors.toMap(e -> e[i], e -> e)); } public static void main(String[] args){ String firstarray[][] = { {"Adam","01-Dec-1980","Commerce","Kansas"}, {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}, {"Nick","09-06-1974","History","Johanesburg"}, {"Bruce","13-08-1975","Philosophy","Seattle"}}; String secondarray[][] = { {"Adam","01-Dec-1980","Commerce","Kansas"}, {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}, {"Sujay Muramalla","08-Jan-1985","Arts","London"}}; Map<String,String[]> firstMap = arrayToMap(firstarray, 0); Map<String,String[]> secondMap = arrayToMap(secondarray, 0); secondMap.keySet().removeAll(firstMap.keySet()); firstMap.putAll(secondMap); String[][] result = firstMap.values().stream().toArray(String[][]::new); //output Arrays.stream(result).forEach(e ->{ System.out.println(Arrays.toString(e)); }); } sidenote: in arrayToMap you can choose which column you use as key. And the logic could be even reduced to this 3 lines: Map<String,String[]> firstMap = arrayToMap(firstarray, 0); firstMap.putAll(arrayToMap(secondarray, 0)); String[][] result = firstMap.values().stream().toArray(String[][]::new); since inserting a value with the same key overwrites the existing one and you get the same if the values are the same in case of equal keys.
A simple an efficient way to do it (if you don't care about ordering) is the following: Time complexity: O(nlog(n)) Space complexity: O(n+m) import java.util.Arrays; public class Main { public static void main(String ... args) { String firstarray[][] = { {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}, {"Nick","09-06-1974","History","Johanesburg"}, {"Bruce","13-08-1975","Philosophy","Seattle"}}; String secondarray[][] = { {"Adam","01-Dec-1980","Commerce","Kansas"}, {"John","04-Feb-1982","Economics","Leeds"}, {"Mathias","08-Jan-1985","Arts","London"}}; String result [][] = new String[firstarray.length + secondarray.length][firstarray[0].length]; // sort firstarray java.util.Arrays.sort(firstarray, new java.util.Comparator<String[]>() { public int compare(String [] a, String[] b) { return a[0].compareTo(b[0]); } }); //sort secondarray java.util.Arrays.sort(secondarray, new java.util.Comparator<String[]>() { public int compare(String [] a, String[] b) { return a[0].compareTo(b[0]); } }); int i = 0, j=0, k=0, cmp ; for ( ;i < secondarray.length && j< firstarray.length;) { cmp = firstarray[i][0].compareTo(secondarray[j][0]); if(cmp ==0) { System.arraycopy(firstarray[i], 0, result[k++], 0, 4); i++; j++; }else if( cmp <0){ System.arraycopy(firstarray[i], 0, result[k++], 0, 4); i++; } else { System.arraycopy(secondarray[j], 0, result[k++], 0, 4); j++; } } // copy the remaining if any from firstarray to the result for (; i < firstarray.length; i++) { System.arraycopy(firstarray[i], 0, result[k++], 0, 4); } // copy the remaining if any from secondarray to the result for (; j < secondarray.length; j++) { System.arraycopy(secondarray[j], 0, result[k++], 0, 4); } //resize it secondarray = Arrays.copyOf(result, k); // just print the secondarray for (int x = 0; x < secondarray.length; x++) { for (int y = 0; y < 4; y++) { System.out.print(secondarray[x][y] + ","); } System.out.println(""); } } }
Passing Multiple Generics Into Java Method
Using Java. The goal is to search for a value, given as a generic, in an ArrayList, also given as a generic. My Student class (pertinent parts) public class Student<T> implements Comparable { private String studName; private Integer gradeAverage; public Student(String nameIn, int gradeIn) { studName = nameIn; gradeAverage = gradeIn; } public int compareTo(Object obj) { Student s1 = (Student)obj; return(this.gradeAverage - s1.gradeAverage); } } My Search; thinking there may be a problem with the generic specifications public class SearchMethods<T,S> { public <T extends Comparable, S extends Comparable> void BinarySearch(T[] inputArray, S searchValue) { boolean found = false; for(int i = 0; i < inputArray.length; i++) { T search = inputArray[i]; if(searchValue.compareTo(search) == 0) { System.out.println(searchValue + " is at index " + i); found = true; } } if(found == false) { System.out.println(searchValue + " was not found"); } } } And my main() public static void main(String[] args) { Student studentOne = new Student("James",92); Student studentTwo = new Student("Mary",95); Student studentThree = new Student("Bobbie",82); Student studentFour = new Student("Emily",100); Student studentFive = new Student("Joey",88); ArrayList<Student> studentList = new ArrayList<Student>(); studentList.add(studentOne); studentList.add(studentTwo); studentList.add(studentThree); studentList.add(studentFour); studentList.add(studentFive); SearchMethods<ArrayList, Student> searchMethods = new SearchMethods<ArrayList, Student>(); searchMethods.BinarySearch(studentList, studentOne); //Should print that it was found at index 0 The given compiler error states that an argument mismatch, that ArrayList cannot be converted to T#1[]. But that's the whole point of generics, right?? Interestingly, no analogous error is given for the second type, but maybe the compiler just hasn't read ahead that far. I'm pretty sure my syntax is OK at the class level, so the error is likely with the calling objects in main(). Though, I could be wrong. Thanks in advance!
You need to convert arraylist to an array. Check the argument for Binary Search. Try this: SearchMethods<ArrayList, Student> searchMethods = new SearchMethods<ArrayList, Student>(); searchMethods.BinarySearch(studentList.toArray(new Student[studentList.size()]), studentOne); You could also change BinarySearch where you work with an arraylist. While this is not part of the question, it is important not compute the difference for compareTo or you will get overflow error. Try this: class Student<T> implements Comparable { private String studName; private Integer gradeAverage; public Student(String nameIn, int gradeIn) { studName = nameIn; gradeAverage = gradeIn; } public int compareTo(Object obj) { Student s1 = (Student)obj; if (this.gradeAverage < s1.gradeAverage){ return -1; } if(this.gradeAverage == s1.gradeAverage){ return 0; } return 1; } #Override public String toString(){ return "student name="+studName +" grade average= " + gradeAverage; } }
HashMap Storing only one entry
I'm taking a binary String like this: 010010010000110100001010 as a String, converting it to Integer Array like this: int[] DD = new DD[binString.length()]; char temp = binString.charAt(i); int binData = Character.getNumericValue(temp); DD[i] = binData; and I'm tying to save these Integer values in to HashMap(I have to store into a HashMap as per instructions given to me) like this: Map<String, Integer> toMemory = new HashMap<String, Integer>(); for(int i=0;i<binString.length();i++) { char temp = binString.charAt(i); int binData = Character.getNumericValue(temp); DD[i] = binData; if((DD[i] & (DD[i]-1) ) == 0) { toMemory.put(new String("ON"), new Integer(DD[i])); } else { toMemory.put(new String("ON"), new Integer(DD[i])); } } for(String s: toMemory.keySet()) { if(s.startsWith("ON")) { System.out.println(toMemory.get(s)); } } The issue I'm facing here is that, only one entry is being stored in the HashMap, say {"ON",0}. And no other values are being stored. My expected output is this: {"ON" , 1 , "OFF" , 0, "ON" , 1 .........} Is there any better way to store the values to get my expected output? Any help will be much appreciated. P.S: Please ignore the recurring code, and I'm relatively new to programming.
Your usage of a Map is flawed. Maps take a unique key and return a value. You are trying to use duplicate keys. Instead, look at using a List with a wrapper class: class ClassName { public String status; public int value; public ClassName(String status, int value){ this.status = status; this.value = value; } } List<ClassName> list = new ArrayList(); To add to the list, create a new instance of your class and call List#add: list.add(new ClassName("ON", 1));
as Infuzed Guy said, you are using the Map the wrong way. It's a unique "key to value mapping". As long as you are using several times the same key and want to store all the dada, you need to use a List. Here is what I could come up with the little you gave us: test it here import java.util.LinkedList; import java.util.List; class Main { public static void main(String[] args) { class Tuple<X, Y> { //The wrapper object public final X x; public final Y y; public Tuple(X x, Y y) { //Object constructor this.x = x; this.y = y; } public String toString() //Here for printing purpose { return "\"" + this.x + "\", " + this.y; } } //Note here te use of List List<Tuple> toMemory = new LinkedList<>(); String binString = "10100100101100101011"; int[] DD = new int[binString.length()]; for(int i=0; i < binString.length(); ++i) { //Here I use the char value //to get the by subtraction DD[i] = binString.charAt(i) - '0'; if(DD[i] == 1) //Simple check with the int value { toMemory.add(new Tuple<>("ON", DD[i])); } else { toMemory.add(new Tuple<>("OFF", DD[i])); } } //Print the List System.out.print("{ "); for(Tuple s: toMemory) { System.out.print(s +", "); } System.out.println("}"); } }
Sorting an ArrayList / HashMap with key
I have an ArrayList static ArrayList<term> terms = new ArrayList<term>(); and a HashMap static HashMap<String,ArrayList<Integer>> inverted_index = new HashMap<String,ArrayList<Integer>>(); This is my class term public class term { int docID; String tokenName; public term(String tokenName, int docID) { this.tokenName = tokenName; this.docID = docID; } public int getDocID() { return docID; } public String getTokenName() { return tokenName; } public String toString(){ return tokenName + " " + docID ; }} I want to sort it by tokenName. I did this Collections.sort(terms, new Comparator<term>(){ public int compare(term term1, term term2){ return term1.tokenName.compareTo(term2.tokenName); } }); Now when I print terms, I do get the sorted order. Now I call this function public static void createInvertedIndex(){ inverted_index.clear(); for(int i=0; i<terms.size(); i++){ ArrayList<Integer> doc_list = new ArrayList<Integer>(); if(!inverted_index.containsKey(terms.get(i).tokenName)){ doc_list.add(terms.get(i).docID); if(i+1 < terms.size()){ if(terms.get(i).tokenName.equals(terms.get(i+1).tokenName)){ while((i+1 < terms.size()) && terms.get(i).tokenName.equals(terms.get(i+1).tokenName)) { i++; doc_list.add(terms.get(i).docID); } } } //System.out.println(terms.get(i)); ------ Get Sorted Terms here inverted_index.put(terms.get(i).tokenName, doc_list); } } System.out.println(inverted_index); // ------ Get Unsorted terms in this } I don't get sorted inverted_index. Do I need to sort it too? If so, how to do that? I want the output in sorted order.
inverted_index is a HashMap and HashMap is not sorted. You need to use a SortedMap for this, like TreeMap.
how do you sort group of arrays that are paired to each other?
how do you sort group of arrays that are paired to each other? for example is that if you have an array of student numbers and student names. how can i make student names adjust too. when you sort it by student number? example output of what i wanted to be: unsorted: ID numbers name course 5 jomar IT 3 karen CS sorted (by ID numbers) ID numbers name course 3 karen CS 5 jomar IT I've tried to use TreeMap but there's this problem that if the value of ID numbers are the same, it will overwrite the other and it will print like this: sorted (by ID numbers) ID numbers name course 3 karen CS in reply to Stultuske i tried to use 1 array that contains id num, name, course. its like this: for(int i=0;i<array.length;i++){ String [][] storeAllArray = {{array[i]},{array2[i]},{array3[i]}}; System.out.println(storeAllArray[0][0] + " " + storeAllArray[1][0] + " " + storeAllArray[2][0]); }
public class Student implements Comparable { private int id; private String name; private String course; public Student(int pid, int pname, int pcourse) { id = pid; name = pname; course = pcourse; } #Override public int compareTo(Object o) { return new Integer(id).compareTo(new Integer(((Student)o).getID())); } public int getID() { return id; } public String getName() { return name; } public String getCourse() { return course; } } At that point, you just make an ArrayList (Or whatever collection you like) of Students, and call Collections.sort(~initialized ArrayList~);
If you had a Collection<Student>, you'd sort it like this: Collections.sort(studentList,new Comparator<Student>() { int compareTo(Student s1, Student s2) { return s1.getSomeField().compareTo(s2.getSomeField()); ) }); Basically you pass a Comparator (generated inline here) to Collections.sort() I'd highly recommend against the parallel array version since it's really avoiding the OO nature of Java. But if you REALLY want to do it, you'd have to have a third array that is just the indexes from 1 to number of elements in your array, then you'd have to use a parallel index array and sort it using Arrays.sort() with a Comparator that compares your parallel array's values (instead of the index array) and then you iterator over the sorted index array and print out the elements that match the index of the other array... Really much easier to do it correctly as above.
Part 1: Define your Comparator as following: public class MyComparator implements Comparator<Object[]> { #Override public int compare( Object[] o1, Object[] o2 ) { if ( (int) o1[0] > (int) o2[0] ) return 1; else if ( !((int) o1[0] > (int) o2[0]) ) return -1; else return 0; } } Part 2: And then follow my example code below in your main class: public class MyComparatorTest { public static void main( String[] args ) { List<Object[]> list = new ArrayList<Object[]>(); Object[] o = new Object[3]; o[0] = 2; o[1] = "TWO"; o[2] = "RR"; list.add(o); o = new Object[3]; o[0] = 3; o[1] = "THREE"; o[2] = "GG"; list.add(o); o = new Object[3]; o[0] = 1; o[1] = "ONE"; o[2] = "TT"; list.add(o); // This sorts your list Collections.sort(list, new MyComparator()); // The following loop is only to show you the sorted list content. for (Object[] obj : list) { for (Object obj2 : obj) { System.out.print(" " + obj2); } System.out.println(); } } } Sample output is: 1 ONE TT 2 TWO RR 3 THREE GG