[英]How to add list of items to an ArrayList<String> in java?
我有需要加載到ArrayList <String>的單詞列表
prefix.properties
vocab\: = http://myweb.in/myvocab#
hydra\: = http://www.w3.org/ns/hydra/core#
schema\: = http://schema.org/
“ vocab:”實際上是“ vocab:”。斜杠(\\)用於讀取冒號(:)字符,因為它是特殊字符。
Dictionary.java
public class Dictionary {
public static ArrayList<String> prefix = new ArrayList<>();
static {
Properties properties = new Properties();
InputStream input = null;
input = ClassLoader.getSystemResourceAsStream("prefix.properties");
System.out.println(input!=null);
try {
properties.load(input);
} catch (IOException e) {
e.printStackTrace();
}
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
for(Map.Entry<Object, Object> E : entries)
{
prefix.add(E.getKey().toString());
prefix.add(E.getValue().toString());
}
}
}
在Dictionary.java中,ArrayList前綴將具有
prefix = [
"vocab:",
"http://myweb.in/myvocab#",
"hydra:",
"http://www.w3.org/ns/hydra/core#",
"schema:",
"http://schema.org/"
]
我正在查詢另一個類中的一些數據。 例如:
public class QueryClass
{
public ArrayList<String> queryResult(String findKey)
{
ArrayList<String> result = new ArrayList<String>();
ArrayList<String> prefix = Dictionary.prefix;
Iterator<String> iterator = prefix.iterator();
while (iterator.hasNext())
{
String currentKey = iterator.next()+findKey;
/**
Here my logic to search data with this currentKey
*/
}
return result;
}
}
問題:
我想避免從.properties文件加載此方法,因為當.properties文件提供存儲數據的(鍵,值)對方式時,可能存在奇數個元素。
為什么我必須從單獨的文件加載? 因為將來我將不得不添加更多的關鍵字/字符串,這就是為什么我將其放在prefix.properties文件中的原因。
有其他替代方法嗎?
不要重新發明輪子。
如果可以定義文件格式,則只需使用java屬性。
您會看到,Properties類具有方法getProperty(String,String) ,其中第二個參數可用於傳遞默認值。 可以使用該方法來獲取不包含值的鍵。
我會非常小心地發明自己的格式; 相反,我將研究重用已有內容的方法。 編寫代碼類似於修建道路:人們忘記了,每條新修建的道路都會轉化為未來的維護工作。
此外:您可以通過調用list.add(strValue)
將字符串值添加到字符串列表中。 僅此而已。
編輯您的評論:當您不想要“ java屬性”時; 然后考慮使用其他格式。 例如,您可能以某種基於JSON的格式持久化數據。 然后只需使用一些現有的JSON解析器。 實際上,您的數據幾乎已經看起來像JSON。
我不確定為什么需要使用ArrayList,但是如果要傳遞這些屬性鍵/值,則有2種更好的方法:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.