String joining in Java 8 and more

Torbjørn Kristoffersen
1 min readApr 13, 2015

--

So trivial — but I’m still discovering new features such as this in Java 8.

String message = String.join("_", "Java", "8", "is", "neat");

Returns “Java_8_is_neat”.

Also check out StringJoiner, which when used with streams you can use like this:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
String commaSeparatedNumbers = numbers.stream()
.map(i -> i.toString())
.collect(Collectors.joining(", "));

Also check out java.util.Stream.Collectors, which makes Java 8 even more interesting. Some examples below.

// Compute sum of salaries of employee
int total = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));

// Group employees by department
Map<Department, List<Employee>> byDept
= employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));

// Compute sum of salaries by department
Map<Department, Integer> totalByDept
= employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.summingInt(Employee::getSalary)));

// Partition students into passing and failing
Map<Boolean, List<Student>> passingFailing =
students.stream()
.collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));

Neat huh. (Note, these examples came from the JDK manual)

--

--