7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

List型同士で差分を求める

Last updated at Posted at 2016-12-13

List型同士で、SQLのminus演算子みたいなの(←伝われ)ができたらいいのに、と思って調べてみたところ、Apache Commonsに便利なのがあった。

Sample.java
List<String> list1 = Arrays.asList("a", "b", "e", "f");
List<String> list2 = Arrays.asList("a", "b", "c", "d", "e");

// list1にあってlist2にないものを抽出
@SuppressWarnings("unchecked")
Collection<String> result = CollectionUtils.subtract(list1, list2);

System.out.println(result.toString()); // => [f]

CollectionUtils#subtract() の中身としては、第1引数(list1)をもとにArrayListを作って、第2引数(list2)をイテレータでぐるぐる回して1件ずつremoveしているだけのようなので、第1引数(list1)の並び順が保障されている模様。ただ、然るべきデータ型に詰めてやるのが正しいような気はする。

危うく↓みたいな地味に面倒なコードを量産するところだった。

List<String> result = new ArrayList<String>(list1);
result.removeAll(list2);
7
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?