简体   繁体   English

根据int升序组织2D数组

[英]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. 我正在尝试将PV从字符串解析为int,但是它将不能与return语句一起使用。 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). 您正在比较名称而不是整数,然后尝试将其中之一解析为一个int(如果您的代码通过编译,则将引发异常),然后将一个String与一个int(不通过编译)进行比较。

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);
                  }
                });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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