集合想象一下下面的对象过滤和转化使用谷歌番石榴
class Trip {
String name;
int numOfTravellers;
DateMidnight from;
DateMidnight too;
}
我写了一个手动递归滤波和Java的变换方法。不过,我认为这可以使用谷歌Guava更雄辩地编写。
有人可以帮助我,并告诉我如何可以重写这个以提高可读性吗?
基本上,这个方法呢,是定位相同的条目,并通过改变日期字段
List<Trip> combineEqual(List<Trip> list) {
int n = list.size() - 1;
for (int i = n; i >= 0; i--) {
for (int j = n; j >= 0; j--) {
if (i == j) {
continue;
}
if (shouldCombineEqual(list.get(i), list.get(j))) {
Trip combined = combine(list.get(i), list.get(j));
list.remove(i);
list.remove(j);
list.add(Math.min(i, j), combined);
return combineEqual(liste);
}
}
}
return list;
}
private boolean shouldCombineEqual(Trip a, Trip b) {
return shouldCombineWith(a, b) || shouldCombineWith(b, a);
}
private boolean shouldCombineWith(Trip a, Trip b) {
return a.too() != null
&& a.too().plusDays(1).equals(b.from)
&& areEqual(a, b);
}
private boolean areEqual(Trip a, Trip b) {
return equal(a.name,b.name) && equal(a.numOfTravellers, b.numOfTravellers);
}
private boolean equal(Object a, Object b) {
return a == null && b == null || a != null && a.equals(b);
}
private Trip combineEqual(Trip a, Trip b) {
Trip copy = copy(a); //Just a copy method
if (a.from.isAfter(b.from)) {
Trip tmp = a;
a = b;
b = tmp;
} // a is now the one with the earliest too date
copy.from = a.from;
copy.too = b.too;
return copy;
}
我认为迭代和递归的组合肯定会降低可读性。也许你可以在这里只用一个for循环来使用地图。列表中的每个元素都会进入地图或与地图中的值结合使用。 –