jdc987
jdc987

Reputation: 743

How would I specify a sort order for my data in my ArrayList in java?

I have an array that holds the ranks of playing cards: A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K. (The "T" represents the 10).

I have all of these stored in an ArrayList.

For example, I have an ArrayList that represents the clubs and has all of the card ranks in it:

ArrayList<Character> clubs = new ArrayList<Character>();

If I print all of the elements in this ArrayList, they print out in the following order:

3 2 4 5 6 8 7 9 T J Q K A 

I then added this to sort the collection:

Collections.sort(clubs);

With the collection sort, it prints the elements in this order:

2 3 4 5 6 7 8 9 A J K Q T

How can I make it so that it prints in this order: ?

A 2 3 4 5 6 7 8 9 T J Q K

Upvotes: 0

Views: 246

Answers (4)

cyon
cyon

Reputation: 9538

As an alternative solution to implementing your own Comparator consider using Google Guava. This library contains many helpful utility classes and functions.

It provides the class Ordering which makes this quite simple:

import com.google.common.collect.Lists;
import com.google.common.collect.Ordering;

//explicitly state the ordering
Ordering<String> ordering = Ordering.explicit("A","1","2","K");

//create unsorted list
List<String> list = Lists.newArrayList("1","1","A","2","K","K","1","A");

System.out.println(ordering.sortedCopy(list)); //sort, but not in place

Collections.sort(list, ordering); //in place sort
System.out.println(list); 

Upvotes: 0

cmd
cmd

Reputation: 11841

Implement java.util.Comparator

public class CharacterComparator implements Comparator<Character> {
    public int compare(Character o1, Character o2) { 
        // ...

Then call sort

List<Character> characters = ...
Collections.sort(characters, new CharacterComparator());

Upvotes: 1

Sajan Chandran
Sajan Chandran

Reputation: 11487

You need to implement your own comparator

public class CardComparator implements Comparator<Character>{
  public int compare(Character c1, Character c2){
   //implement your own logic for comparing.
   }
}

Once its implemented, you should invoke

Collections.sort(clubs, new CardComparator);

Upvotes: 1

Ruben Serrate
Ruben Serrate

Reputation: 2783

   Collections.sort(list, new Comparator<String>() {
        public int compare(String a, String b) {
            //write here the easy code to provide you the right order
            //return -1 if a should appear before b or 1 otherwise
        }

    });

Upvotes: 1

Related Questions