简体   繁体   中英

Organize a 2D array in ascending order based on an int

I've looked around and couldn't find a question as similar to mine. I have these two strings insert into the array. I need it to organize in an ascending order.

final String[][] customer = new String [][]{
    new String[] {"Mary Smith","86"},
    new String[] {"John Doe","100"},
    new String[] {"Maria Garcia","93"},
    new String[] {"Rajesh Patel","91"},
    new String[] {"Malia AlFaleh","105"},
    new String[] {"Li Sung ","100"},
    new String[] {"Jamal Brown","103"},
    new String[] {"Latisha Ford","108"},
    new String[] {"Su Chan","107"},
    new String[] {"Bob O'Leary","33"},
    new String[] {"Aziz Gupta","88"},
    new String[] {"Roman Zwykowicz","97"},
    new String[] {"Roberto Miguel Rodriguez","111"},
    new String[] {"Josh Miller","104"},
    new String[] {"Rosie O'Brien","50"},
    new String[] {"Stan Anderson","96"},
    new String[] {"Bob O'Leary Sr.","47"},
    new String[] {"Lynn VanderCook","109"},
    new String[] {"Mohsin Waleed","117"},
    new String[] {"Abdalla AlSaid","120"},
    new String[] {"Ling Yin","107"},
    new String[] {"Jim O'Leary sr.","39"},
};

Right here is where the issue sits. I am trying to parse PV from a string to an int, but it won't work with the return statement. Any ideas how I can compare and make the lowest number get stored at the top?

Arrays.sort(customer, new Comparator<String[]>() {
        @Override
        public int compare(final String[] name, final String[] PV) {
            final String temp1 = name[0];
            final int temp2 = Integer.parseInt(PV[0]);
            return temp1.compareTo(temp2);
        }
});

for (final String[] s : customer) {
    System.out.println(s[0] + " " + s[1]);
}

You are comparing the names instead of the integers, and you try to parse one of them to an int (which would throw an exception if your code passed compilation) and compare a String to an int (which doesn't pass compilation).

Try :

                Arrays.sort(customer, new Comparator<String[]>() {
                  @Override
                  public int compare(final String[] first, final String[] second) {
                    final Integer temp1 = Integer.valueOf(first[1]);
                    final Integer temp2 = Integer.valueOf(second[1]);
                    return temp1.compareTo(temp2);
                  }
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM