String operations - Learn Java 8 with examples

Example 1: Splitting Strings With Stream API

Split a white space separated String into a list of String using Stream API
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DriverClass {
public static void main(String[] args) {
String str = "I love my country";
Stream.of(str.split(" "))
.map(elem -> new String(elem))
.collect(Collectors.toList()).forEach(System.out::println);

}
}
Output:
I
love
my
country


Example 2: Reverse a string in Java 8 

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class DriverClass {
public static void main(String[] args) {
String str = "knowledgefactory";
String reverse = Stream.of(str).map(o ->
                        new StringBuilder(o).reverse()).collect(Collectors.joining());
System.out.println(reverse);
}
}
Output:
yrotcafegdelwonk


Example 3: Find duplicate characters in a string and count the number of occurances using Java 8

import java.util.Map;
import java.util.stream.Collectors;

public class DriverClass {
public static void main(String[] args) {
String str = "knowledgefactory";
Map<String, Long> s = str.chars()
.mapToObj(i -> (char) i)
.collect(Collectors.groupingBy(Object::toString,
                      Collectors.counting()));
System.out.println(s);
}
}
Output:
{a=1, c=1, d=1, e=2, f=1, g=1, k=1, l=1, n=1, o=2, r=1, t=1, w=1, y=1}


More ... 

Popular posts from this blog

Spring boot video streaming example-HTML5

DataTable-Pagination example with Spring boot, jQuery and ajax

10 Best Job Posting Sites 2021-2022

Spring boot web project free download:User Registration System

Spring Boot + JPA/Hibernate One to Many mapping example

5 Hardest Puzzle,100% fail answers

Java security AES,SHA256,SHA512,MD5-Spring Boot Project Free Download

Spring Boot-AngularJS-Bootstrap-JPA-CRUD

ReactJS - Bootstrap - Buttons

Spring Boot file upload/download example