Yasin
Yasin

Reputation: 133

How do I group by a part of a key of a Java map?

How do I group by a part of a key of a Java map?

For example: my keys are 12A, 12B, 12C, 13A, 13B, 13D and I want to group starting with the prefix number and then with characters in the hashmap as 12(A,B,C) 13(A,B,D) and after again add a new object to the hash map.

My object type: Map <String, BookingClass>

Object key e.g: '12A'

242G=BookingClass [classCode=G, seatsAvailable=,
242E=BookingClass [classCode=E, seatsAvailable=,
121D=BookingClass [classCode=D, seatsAvailable=,
121C=BookingClass [classCode=C, seatsAvailable=,
242B=BookingClass [classCode=B, seatsAvailable=,
242A=BookingClass [classCode=A, seatsAvailable=,
242O=BookingClass

Upvotes: 1

Views: 322

Answers (1)

rghome
rghome

Reputation: 8841

You have two possibilities.

First, you can store your data as a map of maps. For example:

Map<String, Map<String,BookingClass>>

Second, you can use a TreeMap. This type of map is sorted and you can find keys in a given range. So assuming that the second part of your key is an upper-case letter and that 'A' is the minimum and 'Z' is the maximum, then you can find the range from, for example, 12A to 12Z or anything in betweeen.

The methods floorKey and ceilingKey can find the first and last keys.

The method:

public NavigableMap<K,V> subMap(K fromKey,
                       boolean fromInclusive,
                       K toKey,
                       boolean toInclusive)

can return you a submap between two keys which you can then navigate over.

Please see theAPI documenation for more details:

https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html

Upvotes: 2

Related Questions