要将属性列表转换为映射,让我们首先创建一个Properties类的对象-
=Properties p = new Properties();
现在,用于setProperty()
设置键值对-
p.setProperty("P", "1"); p.setProperty("Q", "2"); p.setProperty("R", "3"); p.setProperty("S", "4"); p.setProperty("T", "5"); p.setProperty("U", "6");
这样,以下是“属性”列表如何转换为Map的方式-
HashMap<String, String>map = new HashMap<String, String>((Map) p);
import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.Set; public class Demo { public static void main(String args[]) { Properties p = new Properties(); p.setProperty("P", "1"); p.setProperty("Q", "2"); p.setProperty("R", "3"); p.setProperty("S", "4"); p.setProperty("T", "5"); p.setProperty("U", "6"); p.setProperty("V", "7"); HashMap<String, String>map = new HashMap<String, String>((Map) p); Set<Map.Entry<String, String>>set = map.entrySet(); System.out.println("Key and Value of the Map... "); for (Map.Entry<String, String>m: set) { System.out.print(m.getKey() + ": "); System.out.println(m.getValue()); } } }
输出结果
Key and Value of the Map... P: 1 Q: 2 R: 3 S: 4 T: 5 U: 6 V: 7