[英]Re-arrange a list of objects with a criteria on a property (not ascending/descending)
我有一个对象列表(例如Office对象),它具有诸如ID,名称,位置,强度之类的属性。 现在,假设字段位置具有来自特定集合的值(例如3个可能的值,纽约,加利福尼亚,犹他州)。 现在,我要在位置属性上重新排列此列表,以使带有位置属性的Office对象(纽约为首)在列表中排在首位,其次是加利福尼亚州的犹他州。 因此,基本上这不是升序或降序,而是我为该属性设置的条件。 用Java实现此功能的最有效方法是什么?
我首先想到了使用Comprator,但我不想简单地按升序/降序排序,而是按照如上所述的指定标准进行排序。 不知道,我是否也可以使用COmparator,如果可以,如何使用。 而且,如果没有,那么另一种最有效的方法是什么?
简单,不能排除,理想情况下需要包含所有位置:
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());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.