I'm trying to read Java system properties at runtime, filter based on an includes list (hard coded here but normally injected in via properties file) and finally sorted by key and converted to a Map<String, String>.  This is what I've come up with but not sure if it's the most elegant solution.
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)
    );
I'm keen to know if the code can be tidied up.
How about reversing it and using a stream of the includes list instead? This way, you don't have to unpack those map entries all the time, you can just use sorted, and if includes only includes valid properties, you might not even need the filter. (Also, lookup in the map is faster than lookup in the list, but that probably does not matter much.)
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)
    );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With