/ ハッシュマップ内のリストを2次元配列に変換 - java、配列、linked-list、hashmap

ハッシュマップのリストを2次元配列に変換する - java、arrays、linked-list、hashmap

だから私は "として定義されたハッシュマップ: hashmap<String,LinkedList<node>>。 ノードクラスには2つのフィールドaとbがあります。

必要な文字列値がいくつかあります。情報。 私がやりたいことは、ハッシュマップを調べて、 "a"フィールドのリストを2次元配列に取得した各値に関連付けられているLinkedlistsを探すことです。

そのため、文字列値 "animal"のすべての "a"フィールドは、2次元配列の最初の配列になります。文字列値 "humans"のすべての "a"フィールドは2番目の配列になり、以下同様に続きます。

私はその種類が混乱しているのを知っていますが、私はあなたがポイントを得ることを望みます。

回答:

回答№1は0

2次元配列ではなくリストのリストを使用することを検討する必要があります。行数と列数が非常に大きくなり、それぞれの初期サイズが事前にわからない場合があるためです。

指定しなかったので、いくつか仮定しました。特定のシナリオに合わせて機能するように、必要に応じて変更を加えることができます。下記の仮定を参照してください。

前提

  1. あなたが気にする「弦」、すなわち「動物」、「人間」はあなたの鍵です。 hashMap.
  2. フィールド aNode クラスはタイプ String
  3. あなたが気にするすべての文字列のリストがあります

実装

public static void main(String[] args) throws URISyntaxException, IOException {
Map<String, LinkedList<Node>> hashMap = new HashMap<String, LinkedList<Node>>();
List<List<String>> multiDemList = new ArrayList<List<String>>(); //Once the method is done this will contain your 2D list
List<String> needInfoOn = new ArrayList<String>(); //This should contain all of the HashMap Keys you are interested in i.e. Animal, Human keys

for(String s: needInfoOn){
if(!hashMap.containsKey(s)) continue; //if the map doesnt contain this string then skip to the next so we dont add empty rows in our multidimensional array. remove this line if you want empty rows
List<String> list = BuildTypeAList(hashMap, s);
multiDemList.add(list);
}
}

private static List<String> BuildTypeAList(Map<String, LinkedList<Node>> map, String s) {
LinkedList<Node> linkedList = map.get(s);
ArrayList<String> arrList = new ArrayList<String>();
for(Node n: linkedList) {
arrList.add(n.a);
}
return arrList;
}

private static class Node {
String a;
String b;
}