看起来您正在尝试创建会拆分的字典
keyWord rest of the line
进入keyWord 和rest of the line。
假设我有 input.txt 文件,我的应用可以读取该文件,其内容看起来像
foo description of foo
bar very long description of bar
将其放入地图的代码如下所示:
//I will fill my list with lines from file
List<String> lines = Files.readAllLines(Paths.get("input.txt"));
Map<String, String> dictionary = new LinkedHashMap<>();
// LinkedHashMap - preserves order of insertion
// if you don't need to preserve it use HashMap
// if you want to sort elements by value of key
// use TreeMap
//lets split each line to key and value like you already do
//and put it into dictionary
for (String line : lines){
String[] tokens = line.split("\\s+",2); //split on one (or more continues whitespaces)
//but limit size of array to 2
dictionary.put(tokens[0], tokens[1]); //I assume "rest of the line" is mandatory,
//otherwise tokens[1] will not exist
}
您可以通过迭代其条目集(所有键值对)来打印生成映射的内容:
//lets print content of map
for (Map.Entry<String, String> pair : dictionary.entrySet()){
System.out.println(pair.getKey()+" -> "+pair.getValue());
}
现在要从地图中获取单个元素,我们可以使用get(key),如果地图中不存在键将返回null,所以如果你想避免null,你可以使用getOrDefault(key, alternativeValue),如果@ 987654334@ 将不存在地图将返回alternativeValue:
String definition = dictionary.get("foo");
//if you want to return some predefined value in case "foo" will not be
//present in dictionary you can use:
//String definition = dictionary.getOrDefault("foo","--there is no such word in dictionary--");
System.out.println("definition for key \"foo\" is: "+definition);
输出:
foo -> description of foo
bar -> very long description of bar
definition for key "foo" is: description of foo
要运行此示例,您将需要这些类
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
您的 IDE 应该能够为您生成此导入(在 Eclipse 中使用 Ctrl+Shift+O)
更新:
不幸的是Map 没有get(index) 方法。但是,当您使用键值对填充数组时,您可以创建 Map.Entry 元素中的 List,这些元素具有 size 和 get 方法。为此,您可以简单地使用复制构造函数,例如
Random r = new Random();
List<Map.Entry<String, String>> allPairs = new ArrayList<>(dictionary.entrySet());
// list will be filled with content from this set ^^^^^^^^^^^^^^^^^^^^^
int randomIndex = r.nextInt(allPairs.size());
Map.Entry<String, String> randomEntry = allPairs.get(randomIndex);
System.out.println(randomEntry.getKey());
System.out.println(randomEntry.getValue());