簡單,不能排除與理想需要包含所有位置:
public static void rearrangeSort(List<Office> source, String... locations) {
List<String> locs = Arrays.asList(locations);
Collections.sort(source, (o1, o2) -> locs.indexOf(o1.getLocation()) - locs.indexOf(o2.getLocation()));
}
更復雜:
public static List<Office> rearrange(List<Office> source, String... locations) {
Map<String, List<Office>> map = new HashMap<>();
for (Office office : source) {
List<Office> lst = map.get(office.getLocation());
if (lst == null) {
lst = new ArrayList<>();
map.put(office.getLocation(), lst);
}
lst.add(office);
}
List<Office> resultList = new ArrayList<>();
for (String loc : locations) {
List<Office> partial = map.get(loc);
if (partial != null) {
resultList.addAll(partial);
}
}
return resultList;
}
上一頁變異與lambda表達式:
public static List<Office> rearrange2(List<Office> source, String... locations) {
Map<String, List<Office>> map = source.stream().collect(Collectors.toMap(
Office::getLocation,
o -> {List<Office> lst = new ArrayList<>(); lst.add(o); return lst;},
(offices, offices2) -> {offices.addAll(offices2); return offices;}));
return Arrays.asList(locations).stream()
.filter(map::containsKey)
.map(map::get)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
'Collections.sort '可以有一個額外的比較器,您可以製作幾個或即時。 Java 8允許使用非常簡潔的符號,甚至可以組合比較器。 –