NIV*_*GAR 24 java collections properties map set
对于我的程序,我想从属性文件和键的相关值列表中读取一个键.
最近我这样做了
public static Map<String,List<String>>categoryMap = new Hashtable<String, List<String>>();
Properties prop = new Properties();
try {
prop2.load(new FileInputStream(/displayCategerization.properties));
Set<Object> keys = prop.keySet();
List<String> categoryList = new ArrayList<String>();
for (Object key : keys) {
categoryList.add((String)prop2.get(key));
LogDisplayService.categoryMap.put((String)key,categoryList);
}
System.out.println(categoryList);
System.out.println("Category Map :"+LogDisplayService.categoryMap);
keys = null;
prop = null;
} catch (Throwable e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
和我的属性文件如下 -
A=APPLE
A=ALPHABET
A=ANT
B=BAT
B=BALL
B=BUS
Run Code Online (Sandbox Code Playgroud)
我想要密钥A应该有一个包含[APPLE, ALPHABET,ANT]和包含B 的列表[BAT,BALL,BUS].
所以Map应该是这样的,{A=[APPLE, ALPHABET,ANT], B=[BAT,BALL,BUS]}但我得到了
{A=[ANT], B=[BUS]}
我在互联网上搜索这样的方式,但没有发现任何东西.我希望应该有办法.有帮助吗?
DwB*_*DwB 38
尝试将属性编写为逗号分隔列表,然后在加载属性文件后拆分该值.例如
a=one,two,three
b=nine,ten,fourteen
Run Code Online (Sandbox Code Playgroud)
如果在值中使用逗号,也可以使用org.apache.commons.configuration并使用AbstractConfiguration.setListDelimiter(char)方法更改值分隔符.
小智 11
逗号分隔列表选项是最简单的,但如果值可以包含逗号则变得具有挑战性.
以下是a.1,a.2,...方法的示例:
for (String value : getPropertyList(prop, "a"))
{
System.out.println(value);
}
public static List<String> getPropertyList(Properties properties, String name)
{
List<String> result = new ArrayList<String>();
for (Map.Entry<Object, Object> entry : properties.entrySet())
{
if (((String)entry.getKey()).matches("^" + Pattern.quote(name) + "\\.\\d+$"))
{
result.add((String) entry.getValue());
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
113175 次 |
| 最近记录: |