List Comprehension

· tor java python
This blog post is more than two years old. It is preserved here in the hope that it is useful to someone, but please be aware that links may be broken and that opinions expressed here may not reflect my current views. If this is a technical article, it may no longer reflect current best practice.

Still in the process or tidying up the bot behind the @TorAtlas Twitter account, which means I’m still writing Java. I’ve now been exploring “list comprehension"-like techniques using another new Java 8 feature, Streams. Essentially this involves creating lists from lists in an elegant way.

In Python, I would do something like:

runningRelays = [relay for relay in relays if relay['is_running']]

(I know something is happening because writing that example line I had an incredible urge to terminate the line with a semicolon.)

In Java, the equivalent as I would have written it after my undergraduate degree:

List<RelayDetails> runningRelays = new ArrayList<RelayDetails>();
for ( RelayDetails relay : relays ) {
    if ( relay.isRunning() ) {
        runningRelays.add(relay);
    }
}

but using the new Streams API:

List<RelayDetails> runningRelays = relays
    .stream()
    .filter(relay -> relay.isRunning())
    .collect(Collectors.toList());

It’s not as concise as the Python but I feel a lot better writing the latter and I think it’s a lot more readable than the former too.

This is just one example, it’s an incredibly flexible API and I imagine it could have many uses for aggregations in AtlasBot.


If you would like to contact me with comments, please send me an email.
If you would like to support my free software work, you can support me on Patreon or donate via PayPal.