如何从哈希表获取值<整数,哈希表<字符串,整数>> h



如何为给定的外部hashtable key获取内部HashTable的整数值

HashMap<Integer, String[]> map;
Hashtable<Integer,Hashtable<String,Integer>> h = 
new Hashtable<Integer,Hashtable<String,Integer>>();
for(int z = 0;z<Integer.MAX_VALUE;z++) {
String temp4 = map.get(k)[j];
h.put(z, new Hashtable(){{put(temp4,j);}});
}

第一个解决方案是最简单的,但它需要默认的中间值。

Hashtable<Integer, Hashtable<String, Integer>> h = new Hashtable<>();
h.put(1, new Hashtable<String, Integer>() {{put("firstKey", 3);}});
Integer intValue = h.getOrDefault(1, new Hashtable<>()).getOrDefault("firstKey", null);
System.out.println(intValue);

基于流的解决方案:

Optional<Integer> firstValue = h.entrySet().stream()
.filter(e -> e.getKey().equals(1))
.flatMap(e -> e.getValue().entrySet().stream())
.filter(e -> e.getKey().equals("firstKey"))
.map(e -> e.getValue())
.findFirst();
firstValue.ifPresent(System.out::println);

它可以用Optional引入辅助方法。

private static <K,T> Optional<T> from(Map<K, T>  from, K key) {
return (from.containsKey(key)) ? Optional.of(from.get(key)) : Optional.empty();
}

然后它看起来更可读:

from(h, 1)
.flatMap(x -> from(x, "firstKey"))
.ifPresent(System.out::println);

或者在之前的基础上增加另一种方法:

private static <K, T> Function<Map<K, T>, Optional<T>> forKey(K key) {
return (Map<K, T>  from) -> from(from, key);
}

然后它可以写:

Optional.of(h)
.flatMap(forKey(1))
.flatMap(forKey("firstKey"))
.ifPresent(System.out::println);

不是一个优雅的解决方案,仅针对我的需求:

for(Integer key : h.keySet()) {
//System.out.println(key + " "+h.get(key));
Hashtable temp1 = h.get(key);
String key1 = temp1.toString();
key1 = key1.substring(1);
String separator ="=";
int sepPos = key1.lastIndexOf(separator);
key1 = key1.substring(0,sepPos);
Enumeration enu = temp1.elements();
int col = (int)enu.nextElement();
for(int p=0;p<colums;p++)//j moves over columns
{   
if(p == col) {
for(int r = 0;r<rows;r++) {
String temp = fr.get(r)[p];
//System.out.println(" "+temp+ " ");
if(temp.contentEquals(key1)) {
String temp2 = Integer.toString(p);
temp2 = temp2+ "*";
fr.get(r)[p] = temp2; 
}
}
} 
}

最新更新