NestedMap.java
Download NestedMap.java
1: // Demo showing how to create and then access a complex data structure.
2: // This example shows a Map, with String keys and Set<Tuple> values. A "Tuple"
3: // is demo of a generic class of a pair of values.
4: // Using a Set is good for this demo since Tuples are not "Comparable" and
5: // thus cannot be put in a sorted collection.
6: //
7: // Written 3/2017 by Wayne Pollock, Tampa Florida USA
8:
9: import java.util.*;
10:
11: class NestedMap {
12: public static void main ( String[] args ) {
13: Map<String, Set<Tuple<Integer,Integer>>> map =
14: new TreeMap<>();
15:
16: // Add an item to the map, with the key "foo":
17: String key = "foo";
18: // Create a Set named "set" for the value:
19: Set<Tuple<Integer,Integer>> set = new HashSet<>();
20:
21: set.add( new Tuple<Integer,Integer>( 1, 2 ) );
22: set.add( new Tuple<Integer,Integer>( 1, 3 ) );
23: set.add( new Tuple<Integer,Integer>( 2, 2 ) );
24: map.put( key, set );
25:
26: // Add more key-value pairs to the map...
27:
28: // Now access the Tuples from the map:
29: Set<Tuple<Integer,Integer>> result = map.get( key );
30:
31: // Do something with the Tuple; Here, just print it:
32: System.out.print( "Key: " + key + ", value:" );
33: result.forEach( (tuple) -> { System.out.print( " " + tuple ); } );
34: // Same output as when using older (pre-Java 8) techniques:
35: // for (Tuple<Integer,Integer> t : result ) {
36: // System.out.print( " " + t );
37: // }
38:
39: System.out.println();
40: // Could also use t.item1, t.item2, or t.getFirst(), t.getSecond().
41: }
42: }
43:
44:
45: // A generic class where each object is a pair of values (of any types):
46: class Tuple <T1, T2> {
47: public final T1 item1;
48: public final T2 item2;
49:
50: Tuple ( T1 t, T2 s ) {
51: item1 = t;
52: item2 = s;
53: }
54:
55: public T1 getFirst() { return item1; }
56: public T2 getSecond() { return item2; }
57:
58: @Override
59: public String toString() {
60: return String.format( "(%s,%s)", item1, item2 );
61: }
62:
63: // The equals, hashCode, and compareTo methods are left as an exercise
64: // for the reader.
65: }