JavaRush /Java Blog /Random EN /In Java 8 you can concatenate strings
theGrass
Level 24
Саратов

In Java 8 you can concatenate strings

Published in the Random EN group
I'm sure you've been in a situation where you wanted to concatenate multiple lines. If you didn't write in Java, then you probably used a function join()provided to you by the programming language itself. If you wrote in Java, you couldn’t do this for a simple reason - this method didn’t exist. The standard class library in Java provided you with the tools to create GUI applications, to access databases, to send data over the network, to perform XML transformations, or to call methods from third-party libraries. A simple method for concatenating a collection of strings was not included. To do this, you needed one of the many third-party libraries. In Java 8 you can concatenate strings - 1Fortunately, this has come to an end! In Java 8 we can finally concatenate strings! Java 8 added a new class called StringJoiner. As the name suggests, we can use this class to concatenate strings:
StringJoiner joiner = new StringJoiner(",");
joiner.add("foo");
joiner.add("bar");
joiner.add("baz");
String joined = joiner.toString(); // "foo,bar,baz"

// add() calls can be chained
joined = new StringJoiner("-")
.add("foo")
.add("bar")
.add("baz")
.toString(); // "foo-bar-baz"
Stringuses two new static methods join() StringJoiner:
// join(CharSequence delimiter, CharSequence... elements)
String joined = String.join("/", "2014", "10", "28" ); // "2014/10/28"

// join(CharSequence delimiter, Iterable<? extends CharSequence> elements)
List<String> list = Arrays.asList("foo", "bar", "baz");
joined = String.join(";", list); // «foo;bar;baz"
Also, for concatenating strings there is a special one Collectorin the new API using streams:
List<Person> list = Arrays.asList(
 new Person("John", "Smith"),
 new Person("Anna", "Martinez"),
 new Person("Paul", "Watson ")
);

String joinedFirstNames = list.stream()
 .map(Person::getFirstName)
 .collect(Collectors.joining(", ")); // "John, Anna, Paul»
This way we really don't need third party libraries to concatenate strings anymore! Original article
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION