我试图在运行时读取 Java 系统属性,基于 includes
进行过滤列出 (此处硬编码,但通常通过属性文件注入(inject)),最后按键排序并转换为 Map<String, String>
.这是我想出的,但不确定它是否是最优雅的解决方案。
final List<String> includes = Arrays
.asList("java.version", "PID", "os.name", "user.country"); // hard coded here but (usually defined in a properties file)
Map<String, String> systemMap = System.getProperties()
.entrySet().stream()
.filter(s -> includes != null && includes.contains(s.getKey()))
.sorted(Comparator.comparing(
Map.Entry::getKey, Comparator.comparing(e -> (String) e))
)
.collect(Collectors.toMap(
e -> (String) e.getKey(),
e -> (String) e.getValue(),
(e1, e2) -> e2,
LinkedHashMap::new)
);
我很想知道是否可以整理代码。
最佳答案
如何反转它并使用 includes
列表的 stream
代替?这样,您不必一直解压缩那些映射条目,您可以只使用 sorted
,如果 includes
只包含有效属性,您甚至可能不需要过滤器
。 (此外,在 map 中查找比在列表中查找更快,但这可能无关紧要。)
Properties props = System.getProperties();
Map<String, String> systemMap = includes.stream()
.filter(props::containsKey)
.sorted()
.collect(Collectors.toMap(s -> s, props::getProperty,
(e1, e2) -> e2,
LinkedHashMap::new)
);
关于java - 在 Java 8 中将属性过滤/排序到 map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47495683/