[英]How to get value from Hashtable<Integer,Hashtable<String,Integer>> h
How to get integer value of inside HashTable
for a given ouside hashtable key
如何为给定的外部
hashtable key
获取内部HashTable
表的 integer 值
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);}});
}
First solution is the simplest but it needs default intermediate value.第一个解决方案是最简单的,但它需要默认的中间值。
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);
Solution based on streams:基于流的解决方案:
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);
It can be introduced helper method with Optional
.可以通过
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();
}
Then it look more readable:然后它看起来更具可读性:
from(h, 1)
.flatMap(x -> from(x, "firstKey"))
.ifPresent(System.out::println);
Or add another method based on previous:或者在之前的基础上添加另一种方法:
private static <K, T> Function<Map<K, T>, Optional<T>> forKey(K key) {
return (Map<K, T> from) -> from(from, key);
}
And then it can be written:然后可以写成:
Optional.of(h)
.flatMap(forKey(1))
.flatMap(forKey("firstKey"))
.ifPresent(System.out::println);
You could use Map.getOrDefault(...)
method.您可以使用
Map.getOrDefault(...)
方法。 It allows you eliminate alot of "if" constructions.它可以让你消除很多“if”结构。 Have a look at the code:
看一下代码:
Hashtable<Integer, Hashtable<String, Integer>> h = new Hashtable<>();
h.put(1, new Hashtable<String, Integer>() {{put("firstKey", 3);}});
Integer intValue = h.getOrDefault(1, null).getOrDefault("firstKey", null);
System.out.println(intValue);
Output : Output :
3
3
Not an elegant solution, and only specific to my requirement:不是一个优雅的解决方案,只针对我的要求:
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;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.