[英]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? 如何按Java映射的键的一部分分组?
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. 例如:我的键是12A,12B,12C,13A,13B,13D,我想从前缀编号开始分组,然后在哈希图中将字符分组为12(A,B,C)13(A,B,D ),然后再次将新对象添加到哈希图中。
My object type: Map <String, BookingClass>
我的对象类型:
Map <String, BookingClass>
Object key eg: '12A' 对象密钥,例如:“ 12A”
242G=BookingClass [classCode=G, seatsAvailable=,
242G = BookingClass [classCode = G,seatAvailable =,
242E=BookingClass [classCode=E, seatsAvailable=,242E = BookingClass [classCode = E,seatAvailable =,
121D=BookingClass [classCode=D, seatsAvailable=,121D = BookingClass [classCode = D,seatAvailable =,
121C=BookingClass [classCode=C, seatsAvailable=,121C = BookingClass [classCode = C,seatAvailable =,
242B=BookingClass [classCode=B, seatsAvailable=,242B = BookingClass [classCode = B,seatAvailable =,
242A=BookingClass [classCode=A, seatsAvailable=,242A = BookingClass [classCode = A,seatAvailable =,
242O=BookingClass242O = BookingClass
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
. 其次,您可以使用
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.
因此,假设密钥的第二部分是大写字母,并且“ A”是最小字母,“ Z”是最大字母,那么您可以找到从12A到12Z的范围或其他任何范围。
The methods floorKey
and ceilingKey
can find the first and last keys. floorKey
和ceilingKey
方法可以找到第一个和最后一个键。
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: 请参阅API文档以获取更多详细信息:
https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html https://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.