数学 - HashSet の積集合
CoddyのJavaジャーニー「ロジックとフロー」セクションの一部。レッスン 30/59。
2つの集合の共通部分は、両方の集合に含まれる要素だけを含む新しい集合です。Javaでは、retainAll()メソッドを使用して共通部分を計算できます。
まず、新しい2つのHashSetを作成します。
HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);この新しいセットは、最初のセットのすべての要素を含んだ状態で始まります。
HashSet<Integer> intersectionSet = new HashSet<>(set1);次に、2つ目のセットにも含まれる要素だけを残します。retainAll()メソッドを使用します。
intersectionSet.retainAll(set2);
System.out.println("Intersection: " +
intersectionSet);
// 出力: [2]チャレンジ
簡単2 つの整数の HashSet を入力として受け取り、それらの共通部分を計算して、次の形式で出力するメソッド intersectionSets を作成してください。
Intersection: [2]
自分で試してみよう
import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Main {
public static void intersectionSets(HashSet<Integer> set1, HashSet<Integer> set2) {
// ここにコードを書いてください
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 最初の集合のJSON文字列を読み込む(例:[1,2])
String set1String = scanner.nextLine();
// 2番目の集合のJSON文字列を読み込む(例:[2,3])
String set2String = scanner.nextLine();
Type setType = new TypeToken<HashSet<Integer>>(){}.getType();
HashSet<Integer> set1 = new Gson().fromJson(set1String, setType);
HashSet<Integer> set2 = new Gson().fromJson(set2String, setType);
intersectionSets(set1, set2);
}
}このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
ロジックとフローのすべてのレッスン
自分で練習してみよう: Javaオンラインコンパイラ