Have been remove out, sort the result list data is sorted results
CodePudding user response:
According to the thinking of 5 l, give you write a piece of sample code
public class Sample {
Static class User {
String name;
Int the age;
Public User (String name, int age) {enclosing name=name; Enclosing the age=age; }
}
Public static void main (String [] args) {
Try {
List List=new ArrayList (a);
List. The add (new User (" A ", 1));
List. The add (new User (" B ", 1));
List. The add (new User (" C ", 1));
List. The add (new User (" A ", 2));
List. The add (new User (" B ", 2));
List. The add (new User (" B ", 4));
List. The add (new User (" A ", 3));
List. The add (new User (" A ", 4));
List. The add (new User (" A ", 7));
List. The add (new User (" B ", 7));
List. The add (new User (" C ", 4));
Comparator KeyComp=new Comparator () {//name comparator
Public int the compare (String s1, String s2) {
Return to s1.com pareTo (s2);
}
};
Comparator UserComp=new Comparator () {//age comparator
Public int the compare (User u1, the User u2) {
Return u1. Age - u2. Age;
}
};
Map The map=new HashMap<> (a);//grouped by the name
for (int i=0; IThe User u=list. Get (I);
if (! Map. Either containsKey (u.n ame)) {
The map. The put (u.n ame, new ArrayList<> ());
}
Map. Get (u.n ame). The add (u);
}
List Keys=new ArrayList<> (map) keySet ());
Keys. Sort (keyComp);//the map key sort by name
for (int i=0; IMap. Get (keys. Get (I)), sort (userComp);//the value of the map list sort by age
}
List Result=new ArrayList<> (a);//sort the results
While (true) {
for (int i=0; IList The users=map. Get (keys. Get (I));
While (users. The size () & gt; 0) {//key corresponding to the value of the list data circulation processing is
If (result. The size () & gt; 0 {
The User last=result. The get (result. The size () - 1);//on a data
The User cur=users. Get (0);//the current data
If (last) name) equals (cur. Name) & amp; & The last. The age + 2 & lt; Cur. Age) {//until the current sort data does not meet the conditions for
break;
}
}
Result. The add (users. Remove (0));//or removed from the list of value data is inserted into the sorting result in
}
}
If (result. The size ()==list. The size ()) break;//quantity of sorting results are available and the same number before then end
}
for (int i=0; ISystem. Out. Printf (" name: % s, age: % d \ n ", the result, the get (I). The name, the result, the get (I). The age);
}
} the catch (Throwable e) {
e.printStackTrace();
}
}
}