0

次のオブジェクトを想像してください

class Trip {
  String name;
  int numOfTravellers;
  DateMidnight from;
  DateMidnight too;
}

Java で手動の再帰フィルターと変換メソッドを作成しました。しかし、これは Google 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;
}
4

2 に答える 2

2

HashSetを使用するだけです。

まず、旅行オブジェクトで equals と hashcode を定義します。最初のリストをセットに追加します。次に、一致する旅行が既にセットにあるかどうかを確認する 2 番目のリストを繰り返します。何かのようなもの:

    public static Set<Trip> combineEquals(List<Trip> 11, List<Trip> 12) {
    Set<Trip> trips = new HashSet<>(11);
    for ( Trip t: 12) {
        if ( trips.contains(t)) {
            // combine whats in the set with t
        } else {
            trips.add(t);
        }
    }

    return trips;
于 2013-10-03T19:28:38.703 に答える