19
20

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.

Java List の比較

Last updated at Posted at 2015-07-12

Java Doc みたら分かるんですが振る舞い見たほうがパッと思い出しやすいのでしょぼいですがメモ。

Main.java

import org.apache.commons.collections.ListUtils;

public class Main {
    public static void main(String[] args) {
        List<String> sourceList = Arrays.asList(
            new String[]{"a", "b", "1", "c", "2", "d"});
        List<String> targetList = Arrays.asList(
            new String[]{"1", "2", "3"});

        ListUtils.intersection(sourceList, targetList)
            .stream()
            .forEach(l -> System.out.println("intersection : " + l));

        ListUtils.subtract(sourceList, targetList)
            .stream()
            .forEach(l -> System.out.println("subtract : " + l));

        ListUtils.sum(sourceList, targetList)
            .stream()
            .forEach(l -> System.out.println("sum : " + l));

        ListUtils.union(sourceList, targetList)
            .stream()
            .forEach(l -> System.out.println("union : " + l));

    }
}
List<String> sourceList = Arrays.asList(new String[]{"a", "b", "1", "c", "2", "d"});
List<String> targetList = Arrays.asList(new String[]{"1", "2", "3"});

元リストと対象リストを比較して対象リストにある要素を返す
intersection : 1
intersection : 2

元リストから対象リストを差し引いた要素を返す
subtract : a
subtract : b
subtract : c
subtract : d

2つのリストで重複する要素を Distinct して結合(順番はリストの要素順)
sum : a
sum : b
sum : c
sum : d
sum : 1
sum : 2
sum : 3

2つのリストの順番を維持して結合
union : a
union : b
union : 1
union : c
union : 2
union : d
union : 1
union : 2
union : 3
19
20
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
19
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?