Listを使っている時に、重複したアイテムを除外したいなぁーって思うとき、あると思います。
また、Listを指定件数ごとに分割したいとき、あると思います。
-
「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 -
「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を使ってやっちゃうサンプルです。
dependencies {
compile group: 'com.google.guava', name: 'guava', version: '19.0'
}
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)でみごとに分割されていますねー。
参考