List Comprehension
Published:
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.