-2

I have a list with IP address, role and group. I want to firstly sort the the entire list with its group number. And based on the new list, for each group, I want to sort again by the role. Finally, based on the former sort, sort again by the IP address. I can't find a way to achieve my goal and struggle in it for a couple hours, please help, thank you in advance.

for example, the list is like:

{
<192.168.1.1, 1, "group 2">,
<192.168.1.3, 1, "group 1">,    
<192.168.1.7, 2, "group 1">,
<192.168.1.25, 2, "group 1">,
<192.168.1.1, 2, "group 2">
}

Ideally, after three sorts, the output should be something like:

{
<192.168.1.3, 1, "group 1">,
<192.168.1.7, 2, "group 1">,
<192.168.1.25, 2, "group 1">, 
<192.168.1.1, 1, "group 2">,
<192.168.1.1, 2, "group 2">
}
Minwu Yu
  • 311
  • 1
  • 6
  • 24

3 Answers3

0

Create IPComparator, GroupComparator, RoleComparator object. These objects implements Comparator Interface. E.g;

class IPComparator implements Comparator<IP>{
 public compare (IP o1, IP o2){
//code here
}
}

Similarly, class GroupComparator implements Comparator<Group> and class RoleComparator implements Comparator<Role>.

Now firstlogic. collections.sort(items, new GroupComparator()); Second Logic: now go for roles and so on. This should give you idea how to start on. Remember, you have to maintain some sort of history to sort roles and then IP.

neeranzan
  • 131
  • 5
0

You can use system opportunity to sort like Arrays.sort(yourArray) here: Java: Sort an array Also very powerful explanation here.

Vasyl Lyashkevych
  • 1,920
  • 2
  • 23
  • 38
0

Define comparators for each type of sort. Then use Collections.sort(your_list, comparator_you_want_to_use);

Kavitha Karunakaran
  • 1,340
  • 1
  • 17
  • 32