java在desc中对位置的名称进行排序

时间:2018-06-14 10:48:12

标签: java arrays string sorting

从用户处获取n个名称和位置,并按降序

对位置进行排序
public class Test {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        String name[] = new String[5];
        String location[] = new String[5];
        for (int i = 0; i < name.length; i++) {
            System.out.println("enter the name");
            name[i] = sc.nextLine();
            System.out.println("enter the  location");
            location[i] = sc.nextLine();
        }

        Arrays.sort(location, Collections.reverseOrder()); //desc
        System.out.println("Name and location:");
        System.out.println(name[0] + " " + location[0]);
        System.out.println(name[1] + " " + location[1]);
        System.out.println(name[2] + " " + location[2]);
        System.out.println(name[3] + " " + location[3]);
        System.out.println(name[4] + " " + location[4]);  /*here the names are not changed but the locations are comes with sorted order so the names and locations are mis matched. could you please help me?*/
    }
}

2 个答案:

答案 0 :(得分:1)

您可以将名称和位置存储在两个不同的阵列中。然后,您只反转包含该位置的数组的顺序。最快的解决方法是还反转包含名称的数组的顺序:

Arrays.sort(name, Collections.reverseOrder()); // desc name too

但总的来说,将信息存储在两个不同的数组中并且&#34;匹配&#34;是不好的做法。它通过信任数组的顺序相同。您可能需要考虑使用Map代替或构建存储名称和位置的自定义对象,而不是将该对象放入数组或列表中。

答案 1 :(得分:0)

您的位置数组正在排序,您的名称数组将按原样显示,因为这两个数组都未连接,如果您希望将名称映射到该位置,则有两种方法可以实现它。

方法1: 创建一个类名Info,并创建该类的对象数组:

class Info{
   String name, location;
}

创建对象的ArrayList:

ArrayList<Info> info = new ArrayList<>();

根据位置对此列表进行排序。

方法2:只需创建一个TreeMap并将位置存储为键,将名称存储为其值。

TreeMap<String, String> info = new TreeMap<>();
info.put("location","name");
  

注意:如果使用TreeMap,请确保所有位置都是唯一的。因为密钥应该是唯一的。