Random Stuff About Stuff

Java 8 replace loop with lamda

December 01, 2015

So we have upgraded to Java 8 and so there’s the oppurtunity to refactor some things when they are being upgraded for other reasons.

So one of these is converting some loops to lamda’s, when the loops are doing extra logic, a standard loop doesn’t make much sense to play with.

HashMap<String, String> propMap = new HashMap<>();
for (TestObject testObject : properties) {
    if (StringUtils.isNotEmpty(testObject.getPropId())
            && StringUtils.isNotEmpty(testObject.getValue())) {
        propMap.put(testObject.getPropId(), testObject.getValue());
    }
}

Can be turned into this

 Map<String, String> propMap = properties
        .stream()
        .filter(prop -> StringUtils.isNotEmpty(prop.getPropId()) && StringUtils.isNotEmpty(prop.getValue()))
        .collect(Collectors.toMap(TestObject::getPropId, TestObject::getValue));

Better? Well that’s up for debate I think, it’s a bit cleaner once you speak lamda I guess


Written by David Kerwick who lives and works Dublin as a Java Technical Lead.