LoginSignup
1
1

More than 5 years have passed since last update.

Listから重複を除いたうえで指定個数に分割する方法(guavaの場合)

Last updated at Posted at 2016-09-08

Listを使っている時に、重複したアイテムを除外したいなぁーって思うとき、あると思います。
また、Listを指定件数ごとに分割したいとき、あると思います。

  1. 「Listからサクッと重複をのぞく」ために、重複が含まれたListを引数にしてHashSetを作り、それをまたListに戻すという方法を使います

    HashSet (Java Platform SE 8 )
    https://docs.oracle.com/javase/jp/8/docs/api/java/util/HashSet.html

    ※ HashSetを使うと重複アイテムをサクッと除外してくれるんですが、上記にあるように順番がバラバラになったり、null値は取り除いてくれないという条件がありますのであしからず...

    (追記)
    @kacchan6@github さんにからフィードバック頂いて、「LinkedHashSetなら順序を保持」できることを思い出しましたので追記してます。ありがとうございます!
    null値は取り除けません。

    LinkedHashSet (Java Platform SE 8 )
    https://docs.oracle.com/javase/jp/8/docs/api/java/util/LinkedHashSet.html

  2. 「Listを指定個数に分割する」にはLists.partitionを使います

    Lists (Guava: Google Core Libraries for Java 19.0 API)
    http://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Lists.html

この2つの処理をguavaを使ってやっちゃうサンプルです。

build.gradle
dependencies {
    compile group: 'com.google.guava', name: 'guava', version: '19.0'
}
PartitionedListWithoutDuplication.java
import java.util.List;

import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

public class PartitionedListWithoutDuplication {
    public static void main(String... args) {
        List<String> favBands = Lists.newArrayList("Lotus","STS9","Disco Biscuits","New Deal","Flying Lotus","STS9");
        System.out.println(favBands);

        // without duplicate(HashSet)
        List<String> favBandWithoutDups = Lists.newArrayList(Sets.newHashSet(favBands));
        System.out.println(favBandWithoutDups);

        // without duplicate and keep order(LinkedHashSet)
        List<String> favBandWithoutDupsKeepOrder = Lists.newArrayList(Sets.newLinkedHashSet(favBands));
        System.out.println(favBandWithoutDupsKeepOrder);

        // partitioned
        List<List<String>> partitionedLists = Lists.partition(favBandWithoutDupsKeepOrder, 2);
        System.out.println(partitionedLists);
    }
}

実行結果

[Lotus, STS9, Disco Biscuits, New Deal, Flying Lotus, STS9]
[STS9, Flying Lotus, New Deal, Lotus, Disco Biscuits]
[Lotus, STS9, Disco Biscuits, New Deal, Flying Lotus]
[[Lotus, STS9], [Disco Biscuits, New Deal], [Flying Lotus]]

重複していた「STS9」が除外され、さらに指定数(2)でみごとに分割されていますねー。

参考

1
1
3

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
1
1