Thursday, August 23, 2018

Java8 - Array Stream Lambda Expression How to Examples

Stream API Array Lamda 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.

How to remove white spaces from string array in java8?

A declared array of string objects, Some of the string elements contains whitespaces.
Remove/trim of each string object and return string array without whitespaces
Using lambda Stream  map function in java8 
First Convert Arrays to Stream using Arrays.stream(array) method
Once the stream is available, You can use stream class map() method using 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 toArray() method.
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.

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

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);
Map String with count:{a=2, expression=1, java=1, stream=1, of=1, testing=1, This=1, lamda=1, is=1, example=2}

Convert primitive int array to Object array in java8?


First Convert the primitive array to Stream using Arrays.stream() method
Next using boxer() method which takes stream array and converts to Integer of streams
Convert Stream to an array using toArray() to return Integer object Array

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 is
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

For example, Created List of Employee object with each employee object contains id and name.
Convert list to stream using list.stream() method, Pass this stream of objects to mapToInt function to convert to primitive values of streams
Convert to Array from stream using 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 is
[1, 4, 6, 9, 12]

How to sort an array of numbers in Java 8 using stream and lambda?

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 sort numbers in ascending and descending using lambda and stream classes

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 is
[90, 67, 56, 34, 11, 3, 2, 1]
[1, 2, 3, 11, 34, 56, 67, 90]

Related article


EmoticonEmoticon