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 focuses on frequently used Array lambda expression examples using Streams API.
Here are examples that we covered with Java 8 lambda expressions:
- Trimming white spaces in an array of strings
- Counting words in a string
- Converting primitive types to Object types in an array of elements
- Converting Object List to Primitive Array
- Sorting an array using lambda expression in Java 8
- Converting an array to a Stream of Arrays
Convert Array to List using Java 8
You can convert an array to a list in Java before Java 8 using the following lines of code.
Arrays.asList(array)
Java 8 simplifies this using lambda expressions and streams.
Here’s an example to convert an array of numbers and strings into a 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);
}
}
In this example,
- 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
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 Java 8?
Remove or trim each string object from an array and return the string array without whitespaces.
Here’s a step-by-step approach using lambda Stream map function in Java 8:
- Declare an array of string objects; some elements contain whitespaces.
- Convert the array to a Stream using the
Arrays.stream(array)
method. - Use the stream class
map()
method with a lambda expression function to trim each string of the stream. - Once stream modification is done, 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 Java 8
Given a string as a set of words separated by space, this code returns the count of each word repeated in the string.
Following are step by steps
- Create a word string array using a regular expression.
- Create a Stream array using
Arrays.stream(array)
method. - Group the same strings using
Collectors.groupBy
withFunction.identity()
; it is similar to the SQL group by keyword. - Supply grouping elements to the reduction operator with the collect method to return a Map with words 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 Java 8?
Here’s how you can convert a primitive array to an Object array in Java 8.
- First, convert the primitive array to a Stream using the Arrays.stream() method.
- Next, use the boxed() method, which takes the stream array and converts it to an Integer stream.
- Finally, convert the stream to an array using toArray() to return an 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 Java 8?
This example demonstrates converting a List<Object>
to int[]
in Java 8.
- First, create a List of Employee objects, with each employee object containing an id and name.
- Next, convert the list to a stream using the
list.stream()
method. Pass this stream of objects to themapToInt
function to convert to primitive values of streams. - Finally, convert to an array from the 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 Java 8.
- First, convert
IntStream
usingIntStream.of()
method. - Sort using sorted, does boxed, and
mapToInt
reduce operations with aComparator
. - For descending order, use
Comparator.reverseOrder()
. - For ascending order, use the default Comparator.
The below example sorts numbers in ascending and descending order 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.