Tuesday, September 24, 2024

Practical programming with Java collections


String output = names.stream()
      .sorted((name1, name2) -> {
      String[] parts1 = name1.cut up(" ");
      String lastName1 = parts1[parts1.length - 1];
      String[] parts2 = name2.cut up(" ");
      String lastName2 = parts2[parts2.length - 1];
      return lastName2.compareTo(lastName1);
    })
    .map(title -> {
      String[] elements = title.cut up(" ");
      return elements[parts.length - 1];
    })
    .filter(lastName -> lastName.size() >= 5)
    .cut back("", (accumulator, ingredient) -> accumulator + ingredient + ", ");

    System.out.println("outcome: " + output);

This may concatenate all of the strings collectively, joined by a comma. (We’ll have a trailing comma that we may drop off the top.)

cut back offers us an attention-grabbing take a look at a barely extra superior space of streams. Contemplate should you needed to rely the string characters and return an integer worth. How may you do this? The return worth of cut back would need to be an integer, however the accumulator and ingredient args are strings. I’ll depart that for an train, with this Stack Overflow query as one lead, and my introduction to Java stream gatherers as one other.

Reusing operations

We’ve had a reasonably good take a look at the best way it feels to make use of and compose a few of the most vital Java useful operations. One other vital side is code reuse. Say you wanted to make use of that fancy string sorter in a number of locations. In Java, we may create a useful interface to share that operation:

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles