Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering / sorting properties into a map in Java 8

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.

like image 904
bobmarksie Avatar asked Oct 28 '25 21:10

bobmarksie


1 Answers

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)
    );
like image 161
tobias_k Avatar answered Oct 30 '25 12:10

tobias_k