Pure Programmer
Blue Matrix


Cluster Map

Maps (aka Associative Arrays)

L1

This page is under construction. Please come back later.

Maps1.java
import java.util.HashMap;
import java.util.Map;
import org.pureprogrammer.Utils;

public class Maps1 {

	public static void main(String[] args) {
		Map<String, String> dictionary = new HashMap<>();

		System.out.println("dictionary size: " + dictionary.size());
		System.out.println("dictionary is " + (dictionary.isEmpty() ? "empty" : "not empty"));
		dictionary.put("apple", "red");
		dictionary.put("banana", "yellow");
		dictionary.put("cantaloupe", "orange");
		dictionary.put("dragonfruit", "red");
		dictionary.put("elderberry", "purple");

		System.out.println("dictionary size: " + dictionary.size());
		System.out.println("dictionary is " + (dictionary.isEmpty() ? "empty" : "not empty"));

		System.out.println("bananas are " + dictionary.get("banana"));

		String x = "dragonfruit";
		if (dictionary.containsKey(x)) {
			System.out.println(x + " are " + dictionary.get(x));
		} else {
			System.out.println("Can't find " + x);
		}

		x = "fig";
		if (dictionary.containsKey(x)) {
			System.out.println(x + " are " + dictionary.get(x));
		} else {
			System.out.println("Can't find " + x);
		}

		x = "elderberry";
		dictionary.remove(x);
		if (dictionary.containsKey(x)) {
			System.out.println(x + " are " + dictionary.get(x));
		} else {
			System.out.println("Can't find " + x);
		}

		System.out.println(Utils.mapToString(dictionary));
	}
}

Output
$ javac -Xlint Maps1.java $ java -ea Maps1 dictionary size: 0 dictionary is empty dictionary size: 5 dictionary is not empty bananas are yellow dragonfruit are red Can't find fig Can't find elderberry {"banana" => "yellow", "apple" => "red", "dragonfruit" => "red", "cantaloupe" => "orange"}
Maps2.java
import java.util.HashMap;
import java.util.Map;
import org.pureprogrammer.Utils;

public class Maps2 {

	public static void main(String[] args) {
		Map<String, Integer> planetDiameters = Utils.map(new Object[][] {
			{"Mercury", 4879},
			{"Venus", 12103},
			{"Earth", 12756},
			{"Mars", 6794},
			{"Jupiter", 142985},
			{"Saturn", 120534},
			{"Uranus", 51115},
			{"Neptune", 49534},
			{"Pluto", 2374},
			{"Ceres", 946},
			{"Eris", 2326},
			{"Makemake", 1430}
		});

		for (String planet : planetDiameters.keySet()) {
			System.out.println(planet + " has a diameter of " + planetDiameters.get(planet) + " km");
		}
	}
}

Output
$ javac -Xlint Maps2.java $ java -ea Maps2 Earth has a diameter of 12756 km Mars has a diameter of 6794 km Neptune has a diameter of 49534 km Ceres has a diameter of 946 km Jupiter has a diameter of 142985 km Makemake has a diameter of 1430 km Saturn has a diameter of 120534 km Venus has a diameter of 12103 km Eris has a diameter of 2326 km Uranus has a diameter of 51115 km Mercury has a diameter of 4879 km Pluto has a diameter of 2374 km
java

Questions

Projects

More ★'s indicate higher difficulty level.

References