The following examples represent NQ sorting techniques. Store Pilots function is used to fill in the database.
Select all the pilots from the database and sort descending by points.
01public static void getSortedPilots() { 02
ObjectContainer container = database(); 03
try { 04
List result = container.query(new Predicate<Pilot>() { 05
public boolean match(Pilot pilot) { 06
return true; 07
} 08
}, new QueryComparator<Pilot>() { 09
// sort by points 10
public int compare(Pilot p1, Pilot p2) { 11
return p2.getPoints() - p1.getPoints(); 12
} 13
}); 14
listResult(result); 15
} finally { 16
closeDatabase(); 17
} 18
}
Select all pilots, sort descending by name and by points.
01public static void getPilotsSortByNameAndPoints() { 02
ObjectContainer container = database(); 03
try { 04
List result = container.query(new Predicate<Pilot>() { 05
public boolean match(Pilot pilot) { 06
return true; 07
} 08
}, new QueryComparator<Pilot>() { 09
// sort by name then by points: descending 10
public int compare(Pilot p1, Pilot p2) { 11
int result = p1.getName().compareTo(p2.getName()); 12
if (result == 0) { 13
return p1.getPoints() - p2.getPoints(); 14
} else { 15
return -result; 16
} 17
} 18
}); 19
listResult(result); 20
} finally { 21
closeDatabase(); 22
} 23
}
Sort by points using pre-defined comparator.
01public static void getPilotsSortWithComparator() { 02
ObjectContainer container = database(); 03
try { 04
List result = container.query(new Predicate<Pilot>() { 05
public boolean match(Pilot pilot) { 06
return true; 07
} 08
}, new PilotComparator()); 09
listResult(result); 10
} finally { 11
closeDatabase(); 12
} 13
}
01public static class PilotComparator implements Comparator<Pilot> { 02
public int compare(Pilot p1, Pilot p2) { 03
int result = p1.getName().compareTo(p2.getName()); 04
if (result == 0) { 05
return p1.getPoints() - p2.getPoints(); 06
} else { 07
return -result; 08
} 09
} 10
}