Picking an Element

It’s reasonable to expect that picking one element from a collection would be simpler than picking multiple elements. But there are a few complications. Let’s look at the complexity introduced by the habitual approach and then bring in lambda expressions to solve it.

Let’s create a method that will look for an element that starts with a given letter, and print it.

collections/fpij/PickAnElement.java
 
public​ ​static​ ​void​ pickName(
 
final​ ​List​<​String​> names, ​final​ ​String​ startingLetter) {
 
String​ foundName = null;
 
for​(​String​ name : names) {
 
if​(name.startsWith(startingLetter)) {
 
foundName = name;
 
break​;
 
}
 
}
 
System​.out.print(​String​.format(​"A name starting with %s: "​, startingLetter)); ...

Get Functional Programming in Java now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.