{

Java8 - Array Stream Lambda Expression How to Examples


java8 Array Stream Lambda Expression 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.

How to remove white spaces from string array in java8?

Remove/trim each string object 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 Arrays.stream(array) method
  • Once the stream is available, You can use the 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 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 Stream using the Arrays.stream() method
  • Next, using boxer() method which takes stream array and converts to 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 to Int[] in java8_

  • First, Create a List of Employee object with each employee object containing 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 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 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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.