0

I am trying to create a filtered list of seat nos starting from G only, from a main pool of seat nos A1,A2....B1,B2...etc. However, when i try to sort the list, its not happening, plz help:

My code:

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {

    public static void main(String[] args) {

        List<String> Seats = new ArrayList<String>();

        Random rand = new Random();

        //Creating Alphanumeric seatnumbers e.g A1, A2, A3....B1,B2...etc using ASCII values
        for(int i =0;i<100;i++)
        {
            String seatNum = Character.toString(rand.nextInt(35)+65) + (rand.nextInt(14)+1);

            if(!Seats.contains(seatNum))

            Seats.add(seatNum);

        }

        //Create a filtered list of only seat numbers starting with G

         List<String> gSeats = new ArrayList<>();


            Seats.forEach(seat->{

                if(seat.startsWith("G")   )
                {
                    gSeats.add(seat);
                }
            });
            System.out.println("Original G list");
            gSeats.forEach((String g)-> System.out.println(g));

            gSeats.sort((String g1,String g2)-> g1.compareTo(g2));

            System.out.println("\n\nSorted List\n");
            gSeats.forEach((String g)-> System.out.println(g));



    }

}

The output :

enter image description here

Please help where am I going wrong ?

VMi
  • 346
  • 3
  • 16
  • 1
    Does this answer your question? [Sort on a string that may contain a number](https://stackoverflow.com/questions/104599/sort-on-a-string-that-may-contain-a-number) – Sam May 02 '20 at 16:08
  • 3
    It is sorting. Lexicographically. Which means that G100 will always come before G2, for example, because it has no concept that 100 is higher than 2. – Federico klez Culloca May 02 '20 at 16:08

1 Answers1

3

If your items always contain one character followed by a number, you can do this:

seats.sort((o1, o2) -> {
    int firstCharCompare = Character.compare(o1.charAt(0), o2.charAt(0));
    if (firstCharCompare != 0) {
        // return if the first character is different
        // no need to compare numbers
        return firstCharCompare;
    }

    // if both items start with the same character, compare their number values
    int num1 = Integer.parseInt(o1.substring(1));
    int num2 = Integer.parseInt(o2.substring(1));
    return Integer.compare(num1, num2);
});
Miss Chanandler Bong
  • 4,081
  • 10
  • 26
  • 36