整数配列のリストがあります。それらの間の共通の要素を見つける必要があります。私が考えることができるのは、 2つのリストの共通要素にリストされているものの拡張です
Example would be
[1,3,5],
[1,6,7,9,3],
[1,3,10,11]
should result in [1,3]
アレイにも重複はありません。
これを行う簡単な方法はありますか?
整数配列のリストがあります。それらの間の共通の要素を見つける必要があります。私が考えることができるのは、 2つのリストの共通要素にリストされているものの拡張です
Example would be
[1,3,5],
[1,6,7,9,3],
[1,3,10,11]
should result in [1,3]
アレイにも重複はありません。
これを行う簡単な方法はありますか?
リストをセットに変換してからSet.retainAll
、異なるセット間の共通部分のメソッドを使用できます。すべてのセットを交差させると、共通の要素が残り、結果のセットをリストに戻すことができます。
Guavaが提供するSetの交差メソッドを使用できます。ここに小さな例を示します。
public <T> Set<T> intersection(List<T>... list) {
Set<T> result = Sets.newHashSet(list[0]);
for (List<T> numbers : list) {
result = Sets.intersection(result, Sets.newHashSet(numbers));
}
return result;
}
それがあなたを助けることができることを願っています
retainAll
コレクションのメソッドを使用できます。最初の配列リストで配列リストを初期化commons
し、残りの配列リストごとにこれを呼び出しました。
List<List<Integer>> lists = new ArrayList<List<Integer>>();
lists.add(new ArrayList<Integer>(Arrays.asList(1, 3, 5)));
lists.add(new ArrayList<Integer>(Arrays.asList(1, 6, 7, 9, 3)));
lists.add(new ArrayList<Integer>(Arrays.asList(1, 3, 10, 11)));
List<Integer> commons = new ArrayList<Integer>();
commons.addAll(lists.get(1));
for (ListIterator<List<Integer>> iter = lists.listIterator(1); iter.hasNext(); ) {
commons.retainAll(iter.next());
}
System.out.println(commons);
System.out.println(lists.get(1));
Java8を使用
ArrayList retain = list1.stream()
.filter(list2::contains).filter(list3::contains).collect(toList())
すべてのリストに存在する要素を返す関数を探している場合は、
次に、簡単で簡単な方法は、統計を作成することです{<メンバー、オカレンス>}
ここでの条件は、同じリスト間で重複がないことです。
private Set<Integer> getCommonElements(ArrayList<Integer[]> idList)
{
MapList<Integer,Short> stat = new MapList<Integer,Short>();
// Here we count how many times each value occur
for (int i = 0; i < idList.size(); i++)
{
for (int j = 0; j < idList.get(i).size; j++)
{
if (stat.containsKey(idList.get(i)[j]))
{
stat.set(idList.get(i)[j], stat.get(idList.get(i)[j])+1);
}
else
{
stat.add(idList.get(i)[j], 1);
}
}
}
// Here we only keep value that occured in all lists
for (int i = 0; i < stat.size(); i++)
{
if (stat.get(i) < idList.size())
{
stat.remove(i);
i--;
}
}
return stat.keySet();
}
public class ArrayListImpl{
public static void main(String s[]){
ArrayList<Integer> al1=new ArrayList<Integer>();
al1.add(21);al1.add(23);al1.add(25);al1.add(26);
ArrayList<Integer> al2=new ArrayList<Integer>();
al2.add(15);al2.add(16);al2.add(23);al2.add(25);
ArrayList Al3=new ArrayList<Integer>();
al3.addAll(al1);
System.out.println("Al3 Elements :"+al3);
al3.retainAll(al2); //Keeps common elements of (al1 & al2) & removes remaining elements
System.out.println("Common Elements Between Two Array List:"+al3);
}
}
public class commonvalue {
Public static void MyMethod(){
Set<integer> S1 = new set<integer>{1,3,5};
Set<integer> S2 = new set<integer>{1,6,7,9,3};
Set<integer> S3 = new set<integer>{1,3,10,11};
s2.retainall(s1);
s3.retainall(s2);
system.debug(s3);
}
}