/home/wpollock1/public_html/AJava/NestedMap.java
// Demo showing how to create and then access a complex data structure.
// This example shows a Map, with String keys and Set<Tuple> values. A "Tuple"
// is demo of a generic class of a pair of values.
// Using a Set is good for this demo since Tuples are not "Comparable" and
// thus cannot be put in a sorted collection.
//
// Written 3/2017 by Wayne Pollock, Tampa Florida USA
import java.util.*;
class NestedMap {
public static void main ( String[] args ) {
Map<String, Set<Tuple<Integer,Integer>>> map =
new TreeMap<>();
// Add an item to the map, with the key "foo":
String key = "foo";
// Create a Set named "set" for the value:
Set<Tuple<Integer,Integer>> set = new HashSet<>();
set.add( new Tuple<Integer,Integer>( 1, 2 ) );
set.add( new Tuple<Integer,Integer>( 1, 3 ) );
set.add( new Tuple<Integer,Integer>( 2, 2 ) );
map.put( key, set );
// Add more key-value pairs to the map...
// Now access the Tuples from the map:
Set<Tuple<Integer,Integer>> result = map.get( key );
// Do something with the Tuple; Here, just print it:
System.out.print( "Key: " + key + ", value:" );
result.forEach( (tuple) -> { System.out.print( " " + tuple ); } );
// Same output as when using older (pre-Java 8) techniques:
// for (Tuple<Integer,Integer> t : result ) {
// System.out.print( " " + t );
// }
System.out.println();
// Could also use t.item1, t.item2, or t.getFirst(), t.getSecond().
}
}
// A generic class where each object is a pair of values (of any types):
class Tuple <T1, T2> {
public final T1 item1;
public final T2 item2;
Tuple ( T1 t, T2 s ) {
item1 = t;
item2 = s;
}
public T1 getFirst() { return item1; }
public T2 getSecond() { return item2; }
@Override
public String toString() {
return String.format( "(%s,%s)", item1, item2 );
}
// The equals, hashCode, and compareTo methods are left as an exercise
// for the reader.
}