文章目录
- 1. 前言
- 2. 正片
- 1. keySet()方式
- 2. entrySet()方式
- 3. propertyNames()方式
- 4. stringPropertyNames()方式
1. 前言
- 无意有次需求是遍历Properties对象,但突然就不知道怎么遍历了,因此写文章记录一下。
2. 正片
- Properties 是键值对 存储的,key—value,因此遍历方式跟Map基本一致。
1. keySet()方式
public class demo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("1", "11");
properties.put("2", "22");
properties.put("3", "31");
properties.put("4", "41");
Set<Object> keySet = properties.keySet();
for (Object key : keySet) {
System.out.println(key + ": " + properties.get(key));
}
}
}

2. entrySet()方式
public class demo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("1", "11");
properties.put("2", "22");
properties.put("3", "31");
properties.put("4", "41");
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
for (Map.Entry<Object, Object> map : entries) {
System.out.println(map.getKey() + ":" + map.getValue());
}
}
}

3. propertyNames()方式
public class demo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("1", "11");
properties.put("2", "22");
properties.put("3", "31");
properties.put("4", "41");
Enumeration<?> enumeration = properties.propertyNames();
while (enumeration.hasMoreElements()) {
Object key = enumeration.nextElement();
System.out.println(key + ":" + properties.get(key));
}
}
}

4. stringPropertyNames()方式
-
stringPropertyNames() 是把key全部获取封装到Set中,之后直接用增强foreach来操作,但是只是针对key,value都是String类型的情况下,这个是重点。
-
下面是正常使用情况:
public class demo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put("1", "11");
properties.put("2", "22");
properties.put("3", "31");
properties.put("4", "41");
Set<String> keys = properties.stringPropertyNames();
for (String key : keys) {
System.out.println(key + ":" + properties.get(key));
}
}
}

-
如果我把key,value 改成不是String 类型的,如下:
public class demo {
public static void main(String[] args) {
Properties properties = new Properties();
properties.put(1, "11");
properties.put("2", 22);
properties.put("3", 31);
properties.put(4, "41");
Set<String> keys = properties.stringPropertyNames();
System.out.println("keys的size:" + keys.size());
for (String key : keys) {
System.out.println(key + ":" + properties.get(key));
}
}
}

由上可以看出,key,value如果有一个不是String类型,则不会接受。我们从源码角度来看:
public Set<String> stringPropertyNames() {
Hashtable<String, String> h = new Hashtable<>();
enumerateStringProperties(h);
return h.keySet();
}
private synchronized void enumerateStringProperties(Hashtable<String, String> h) {
if (defaults != null) {
defaults.enumerateStringProperties(h);
}
for (Enumeration<?> e = keys() ; e.hasMoreElements() ;) {
Object k = e.nextElement();
Object v = get(k);
if (k instanceof String && v instanceof String) {
h.put((String) k, (String) v);
}
}
}