2017-02-28 14 views
-1

これを行うにはより良い方法がありますか? 私はJava 8を使用しています。ストリームでこれを行いますが、これを行うには何らかの助けが必要です。私はそれを試してみました... removeIf()が動作しませんでした。JavaにはリストAのオブジェクトがリストに含まれていないb

final List<CalendarEventUserConnection> calendarEventUserConnectionsToDelete = new ArrayList<>(); 
    for (final CalendarEventUserConnection existingCalendarEventUserConnection : existingCalendarEventUserConnections) { 
     boolean contains = false; 
     for (final CalendarEventUserConnection newCalendarEventUserConnection : calendarEventUserConnections) { 
      if (newCalendarEventUserConnection.getId() != null 
       && newCalendarEventUserConnection.getId().equals(existingCalendarEventUserConnection.getId())) { 
       contains = true; 
      } 
     } 
     if (contains == false) { 
      calendarEventUserConnectionsToDelete.add(existingCalendarEventUserConnection); 
     } 
    } 
+1

この質問をするには良い方法がありますか?それはほとんど情報を含んでいません。 – Adam

+0

これを行う - 「これ」とは何ですか?あなたが説明できない場合は、確かに –

+0

にはなりません。 20文字以上の変数名は使用しないでください。 '== false'を使わないでください。これは '!'演算子のためのものです。 –

答えて

1

これをストリーム化することができます。リストをフィルタリングして、別のリスト内のものがそれに合っているかどうかを確認し、別のリストで結果を収集するようです。

したがって、filter,anyMatchおよびcollectを使用できます。

final List<CalendarEventUserConnection> toDelete = existingCalendarEventUserConnections.stream() 
    .filter(c -> !calendarEventUserConnections.stream() 
        .map(CalendarEventUserConnection::getId) 
        .anyMatch(id -> id!=null && id.equals(c.getId()))) 
    .collect(Collectors.toList()); 
+0

@assyliasいい考えです。ありがとう – khelwood

0

あなたはListBの

public static <T> List<T> aNotB(List<T> listA, List<T> listB) { 

    List<T> result = new ArrayList(listA); 
    result.removeAll(listB); 

    return result; 
} 

Tequals方法が正しく実装されている場合は、この唯一の作品ではないLISTA上にあり、すべてのオブジェクトを取得したい場合は...

+0

結果は 'equals'がどのように実装されているかによって決まります。これは質問のロジックと異なる場合があります。 – assylias

+0

しかし、その点で問題は非常に開いています...そして他の人...私は 'equals'が正しく実装されていると仮定しました。 –

+1

この質問はオブジェクトの* ids *を比較します。つまり、実際のオブジェクトには 'equals'がオーバーライドさえないかもしれません。 – RealSkeptic

0

あなた自身の検索はO(NxM)です。ここで、Nは1つのリスト内の要素の数であり、他はMです。

calendarEventUserConnectionsのすべてのIDをまとめて1組にすることをおすすめします。

次に、削除リストに設定されているIDのexistingCalendarEventUserConnectionsのすべての要素を収集できます。

あなたのIDは文字列で、これはのようなものになるだろうと仮定:あなたはHashSetを使用することを考慮すると

Set<String> idsToDelete = calendarEventUserConnections.stream() 
          .map(CalendarEventUserConnection::getId) 
          .filter(Objects::nonNull) 
          .collect(Collectors.toCollection(HashSet::new)); 
List<CalendarEventUserConnection> connectionsToDelete = 
          existingCalendarEventUserConnections.stream() 
          .filter(idsToDelete::contains) 
          .collect(Collectors.toList()); 

(未テストコード)

、これはO(M + N)への複雑性を低減するであろうO(MxN)の代わりに

関連する問題