Java8 - Array Stream Lambda Expression How to Examples
Stream API Array Lambda Examples
In my previous post, We covered and learned lambda expressions in java8.
This post is about the frequently used Array lambda expression examples using Streams API.
Following are examples that we learn with java8 lambda expressions
- Java8 trim white spaces in an array of string
- Java8 count of words in a string
- Convert primitive type to Object type in an array of elements
- Convert Object List to Primitive Array
- Array Sort using lambda expression in java8
- Convert Array to Stream of Arrays
Convert Array to List using Java8 with examples
You can convert Array to list before java8 using the below lines of code
Arrays.asList(array)
Java8 simplified using lambda expression and streams.
- Array is declared and initialized with values
- Convert Array to Stream using Arrays.stream() method.
- Convert the Stream of numbers into a Stream of integers using the boxed() method
- Finally, Collect the data from streams using the collect method
Here is an example to convert an array of numbers and strings into an Array of List
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Sort {
public static void main(String[] args) {
int numbers[] = {1, 2, 3, 4, 5};
List<Integer> numbersList = Arrays.stream(numbers).boxed().collect(Collectors.toList());
System.out.println("List of Integers: " + numbersList);
String words[] = {"one","two","three","four"};
List<String> wordsList = Arrays.stream(words).collect(Collectors.toList());
System.out.println("List of Strings: " + wordsList);
}
}
Output:
List of Integers: [1, 2, 3, 4, 5]
List of Strings: [one, two, three, four]
How to remove white spaces from array string in java8?
Remove/trim each string object from an array and return the string array without whitespaces.
Step by step using lambda Stream map function in java8.
- A declared array of string objects, Some of the string elements contain whitespaces.
- First Convert Arrays to Stream using the
Arrays.stream(array)
method - Once the stream is available, You can use the stream class
map()
method using the lambda expression function to trim each string of a stream. - Once stream modification is done, you need to convert the stream to an array using the
toArray()
method.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
String[] stringArray = { "one ", "two ", " three ", " four " };
System.out.println("Original Array: " + Arrays.toString(stringArray));
String[] result = Arrays.stream(stringArray).map(value -> value.trim()).toArray(size -> new String[size]);
System.out.println("Trim Array: " + Arrays.toString(result));
}
}
Original Array: [one, two , three, four ]
Trim Array: [one, two, three, four]
How to find the count of words in a string in java8
Given a String is a set of words separated by space.
This code returns each word count that how many times repeated in a string.
Following are step by steps
- Create a word string array using a regular expression
- Next is to create a Stream array using Arrays.stream(array) method
- Group the same strings using collectors.Groupby with Function. identity()- it is like group by SQL keyword
- Supply grouping elements to reduction operator with collect method return the Map with word and their count
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String stringText = "This is a testing java stream example of a lamda expression example";
String[] word = stringText.trim().split("\\s+");
Map<String, Long> mapWordCount = Arrays.stream(word)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("Map String with count:"+ mapWordCount);
}
}
Output:
Map String with count:{a=2, expression=1, java=1, stream=1, of=1, testing=1, This=1, lamda=1, is=1, example=2}
How to Convert primitive int array to Object array in java8?
- First, Convert the primitive array to a Stream using the
Arrays.stream()
method - Next, using the
boxer() method
which takes the stream array and converts to an Integer of streams - Finally, Convert Stream to an array using
toArray()
to return Integer object Array.
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] primitiveIntArray = {11, 21, 13, 41, 15,61};
Integer[] integerObjectArray=Arrays.stream(primitiveIntArray).boxed().toArray(Integer[]::new);
System.out.println("Integer Object Array: " + Arrays.toString(integerObjectArray));
}
}
Output:
Integer Object Array: [11, 21, 13, 41, 15, 61]
How to convert Object List to Primitive Array in java8?
This is an example for Converting List<Object>
to Int[]
in java8_
- First, Create a List of Employee objects with each employee object containing an id and name.
- Next, Convert the list to stream using the list.stream() method, Pass this stream of objects to mapToInt function to convert to primitive values of streams
- Finally, Convert to Array from stream using the toArray() method
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LamdaExpressionThisExample {
public static void main(String[] args) {
List<Emp> emps = new ArrayList<Emp>();
emps.add(new Emp(1, "one"));
emps.add(new Emp(4, "four"));
emps.add(new Emp(6, "six"));
emps.add(new Emp(9, "nine"));
emps.add(new Emp(12, "tweleve"));
int[] idsArray = emps.stream().mapToInt(Emp::getId).toArray();
System.out.println(Arrays.toString(idsArray));
}
}
class Emp {
Integer id;
String name;
Emp(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Output:
[1, 4, 6, 9, 12]
How to sort an array of numbers in Java 8 using stream and lambda?
Here is a sequence of steps to sort array numbers in java8
- First Convert intstream using IntStream.of() method.
- Sorted using sorted, boxed and mapToInt reduce operations with Comparator
- For descending order - use Comparator.reverseOrder()
- For ascending order - Default Comparator .
The below example sorts numbers in ascending and descending using lambda and stream classes
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int intArray[] = {56,11,1,67,34,3,90,2};
// Sort Descending Order
int[] sortedDescOutput = IntStream.of(intArray)
.boxed()
.sorted(Comparator.reverseOrder())
.mapToInt(i -> i)
.toArray();
// Sort Asecnding Order
int[] sortedAscOutput = IntStream.of(intArray)
.boxed()
.sorted()
.mapToInt(i -> i)
.toArray();
System.out.println(Arrays.toString(sortedDescOutput));
System.out.println(Arrays.toString(sortedAscOutput));
}
}
Output:
[90, 67, 56, 34, 11, 3, 2, 1]
[1, 2, 3, 11, 34, 56, 67, 90]
Conclusion
Learned multiple examples on array streams using lambda expression in java8.