HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Finding the longest string and its length using Java streams

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thelengthjavaitsusingstreamsfindingandlongeststring

Problem

Java 8 streams are my new golden hammer that I try to use as often as possible with often enormous gains in brevity and readability. Getting multiple return values, such as a maximum value and its associated element, is a bit cumbersome though (and requires an additional "pair" class).

Should I go back to "normal Java" for this task or is this syntax preferable? Is there a more concise way?

List names = Arrays.asList("John","Paul","Ringo"); 
Pair longestName = names.stream()
 .map(n->new Pair<>(n,n.length())) // pretend n.length() to be a lengthy operation
 .max(Comparator.comparing(Pair::getB)).get();
System.out.println(longestName.getA()+" "+longestName.getB());


P.S.: With "lengthy operation" I mean long running, as in I don't want to calculate it twice.

Solution

Your concept is fine. My only criticism is in code style, and perhaps you should have a specific/custom container instead of the Pair. getA() and getB() should be getName() and getLength(). This also allows you to use primitive values and not Integer, and removes the confusing generic types.

Also:

  • don't get from Optionals at the stream end.



  • use white-space, it's your friend.



  • use meaningful names for lambda parameters (name is better than n )



The code I would write would look like:

Optional maxOp = names.stream()
                  .map (name -> new Operation(name, name.length()))
                  .max (Comparator.comparingInt(Operation::getLength()));
Operation longest = maxOp.get();

System.out.println(longest.getName() + " " + longest.getLength());

Code Snippets

Optional<Operation> maxOp = names.stream()
                  .map (name -> new Operation(name, name.length()))
                  .max (Comparator.comparingInt(Operation::getLength()));
Operation longest = maxOp.get();

System.out.println(longest.getName() + " " + longest.getLength());

Context

StackExchange Code Review Q#75807, answer score: 2

Revisions (0)

No revisions yet.