简体   繁体   中英

How to sort two arraylists according to their size into a new arraylist

我有两个对象,每个对象都有一个ID和一个列表。我想要第三个arraylist根据列表大小对该对象进行排序。并且仍然具有对应的ID和列表

Here's the approach:

  1. Create a Comparator which can compare two of the "id/list pairs" -- in this case, we compare the list sizes of the list component.

  2. Create an ArrayList of these "id/list pairs".

  3. Use the Collections.sort method to sort the ArrayList , according to the Comparator .

If I understand correctly, there is a id/list pair. Here's one I made:

class IdListPair {
  int id;
  List<?> list;

  IdListPair(int id, List<?> list) {
    this.id = id;
    this.list = list;
  }

  public String toString() {
    return "id: " + id + "; list: " + list;
  }
}

The IdListPair provides a constructor to create the id/list pair, and a toString method which will be used later to show the results of the sort.

Then, we'll have a section that creates an ArrayList , and sorts the list, using a Comparator :

List<IdListPair> pairList = new ArrayList<IdListPair>();
pairList.add(new IdListPair(0, Arrays.asList(1, 2, 3)));
pairList.add(new IdListPair(1, Arrays.asList(1)));
pairList.add(new IdListPair(2, Arrays.asList(1, 2)));

System.out.println("Before: " + pairList);

Collections.sort(pairList, new Comparator<IdListPair>() {
  public int compare(IdListPair o1, IdListPair o2) {
    return o1.list.size() - o2.list.size();
  }

  public boolean equals(Object o) {
    return false;
  }
});

System.out.println("After: " + pairList);

At first, an ArrayList was created with IdListPair that has lists of differing lengths.

Then, the Collections.sort method performs a sort according to the rules provided by the Comparator . A class implementing Comparator needs to provide the compare and equals methods.

Here, a Comparator was made so it will compare the size of the list that each IdListPair object contains in the compare method. The equals method is a dummy method as it isn't used here.

Most of the effort is going to come in writing the correct compare method, so the sorter of Collections.sort can correctly sort the list.

The results were as follows:

Before: [id: 0; list: [1, 2, 3], id: 1; list: [1], id: 2; list: [1, 2]]
After: [id: 1; list: [1], id: 2; list: [1, 2], id: 0; list: [1, 2, 3]]

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