Как получить значение из Hashtable> ч - PullRequest
0 голосов
/ 24 октября 2019

Как получить целочисленное значение внутри HashTable для заданного значения hashtable key

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);}});
}

Ответы [ 2 ]

1 голос
/ 24 октября 2019

Первое решение самое простое, но для него требуется промежуточное значение по умолчанию.

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);
0 голосов
/ 31 октября 2019

Не элегантное решение, а только специфическое для моего требования:

        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; 
                    }
                }
            } 
        }
...