- Mapインターフェースの概要
Mapインターフェースは、各要素がキー(Key)と値(Value)で構成されるペア型のコレクションです。キーと値の間に一対一の関係があり、この関係を「マッピング」と呼びます。Mapから要素にアクセスする際には、指定されたキーを使用して対応する値を取得できます。
- HashMapクラスの利用
HashMapはMapインターフェースの実装クラスで、キーと値のペアを格納します。ただし、HashMapではキーの重複は許されず、順序も保証されていません。以下にHashMapの使用例を示します。
import java.util.*;
public class HashMapExample {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>(); // HashMapオブジェクトの生成
map.put("apple", "りんご"); // キーと値の追加
map.put("banana", "バナナ");
map.put("cherry", "さくらんぼ");
System.out.println("apple: " + map.get("apple")); // キーを使って値を取得
System.out.println("banana: " + map.get("banana"));
System.out.println("cherry: " + map.get("cherry"));
}
}
上記のコードでは、4~6行目でHashMapオブジェクトを作成し、put()メソッドで3つの要素を追加しています。7~9行目では、get()メソッドを使用してそれぞれのキーに対応する値を取得しています。
3. TreeMapクラスの利用
HashMapでは要素の順序が保証されませんが、TreeMapを使用することでキーに基づいて自動的にソートされた順序で要素を管理できます。以下にTreeMapの使用例を示します。
import java.util.*;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap = new TreeMap<>(); // TreeMapオブジェクトの生成
treeMap.put(10, "十");
treeMap.put(5, "五");
treeMap.put(20, "二十");
for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
このコードでは、TreeMapオブジェクトが作成され、整数キーに対して文字列値を割り当てています。for-eachループによって、自動的にソートされた順序でキーと値が表示されます。
4. 自定义比較子を使ったTreeMap
TreeMapはデフォルトで自然順序でのソートを行いますが、独自の比較ロジックを提供することも可能です。以下に、カスタムクラスを持つTreeMapの例を示します。
import java.util.*;
class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return "Product{name='" + name + "', price=" + price + "}";
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
}
public class CustomComparatorExample {
public static void main(String[] args) {
TreeMap<Product, String> productMap = new TreeMap<>(new Comparator<Product>() {
@Override
public int compare(Product p1, Product p2) {
int priceComparison = Double.compare(p1.getPrice(), p2.getPrice());
if (priceComparison != 0) return priceComparison;
return p1.getName().compareTo(p2.getName());
}
});
productMap.put(new Product("Apple", 100), "果物");
productMap.put(new Product("Banana", 50), "果物");
productMap.put(new Product("Carrot", 30), "野菜");
for (Map.Entry<Product, String> entry : productMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
この例では、Productクラスを定義し、価格と名前を基準にしたカスタム比較子をTreeMapに適用しています。
5. 集合の実用例
以下の課題を通じて、ArrayList、HashSet、HashMapの基本的な使い方を確認します。
5.1 課題内容
- 数字1から5を含むArrayListを作成し、すべての要素を出力します。
- 色の文字列(例:"赤"、"青"、"緑")を含むHashSetを作成し、重複する要素を追加して挙動を観察します。
- 国名をキー、首都を値とするHashMapを作成し、全てのエントリを出力します。
5.2 実装例
// ArrayListの例
List<Integer> numberList = new ArrayList<>();
numberList.add(1);
numberList.add(2);
numberList.add(3);
numberList.add(4);
numberList.add(5);
for (Integer num : numberList) {
System.out.println(num);
}
// HashSetの例
Set<String> colorSet = new HashSet<>();
colorSet.add("赤");
colorSet.add("青");
colorSet.add("緑");
colorSet.add("赤"); // 重複する要素は無視される
for (String color : colorSet) {
System.out.println(color);
}
// HashMapの例
Map<String, String> capitals = new HashMap<>();
capitals.put("日本", "東京");
capitals.put("アメリカ", "ワシントンD.C.");
capitals.put("フランス", "パリ");
for (Map.Entry<String, String> entry : capitals.entrySet()) {
System.out.println("国: " + entry.getKey() + ", 首都: " + entry.getValue());
}