↓ Skip to main content
Streams

Java Stream: Examples

·3 mins

Streams are convenient way to reduce the line of codes, but an understanding them is equally challenging. I write this blog, after realising a desperate attempt at solving a trivial problem just took overwhelming time. (Could be that I am getting old, but never late to learn things again)

public class PlaySteams {
    public static void main(String []args) {
        int[] a = new int[] {1,1,1,2,2,2,3,3,3,4,4,4};
        //Stream Sum of the array
        long sum = IntStream.range(0, a.length).count();

        System.out.printf("Sum: %d\n", sum);
        // Maximum
        System.out.printf("Max: %d\n", IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).distinct().max().getAsInt());
        // Minimum
        System.out.printf("Min: %d\n", IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).distinct().min().getAsInt());

        IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).distinct().forEach(x -> System.out.printf("%d ", x));
        System.out.printf("Average (Distinct): %f\n", IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).distinct().average().getAsDouble());

        System.out.printf(" Number of elements : %d\n", IntStream.of(a).asLongStream().count());

        IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).forEach(x -> System.out.printf("%d ", x));
        System.out.printf("Average (All): %f\n", IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).average().getAsDouble());

        List<Integer> listOfIntegers = IntStream.of(a).boxed().collect(Collectors.toList());
        System.out.println(listOfIntegers.toString());

        System.out.println("Length: ");
        System.out.println(listOfIntegers.size());

        // Creating a map
        // 1 -> 3
        // 2 -> 3 ...
        System.out.println(IntStream.range(0, a.length).map(i -> a[i]).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).toString());

        // Using list
        Map<Integer, Long> valueMap = listOfIntegers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(valueMap.toString());

        // Map of indexes
        // Indexes and value of the index
        System.out.println(IntStream.range(0, a.length).boxed().collect(Collectors.groupingBy( i -> a[Integer.valueOf(i)], Collectors.toList())));

    }
}

The example set remains the same for all the invocation.

int[] a = new int[] {1,1,1,2,2,2,3,3,3,4,4,4};

Example - 1:
#

long sum = IntStream.range(0, a.length).count();
System.out.printf("Sum: %d\n", sum);

It simply runs over the length of the array and returns the total number of elements

Sum: 12

Example - 2:
#

Return the maximum

System.out.printf("Max: %d\n", IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).distinct().max().getAsInt());
Max: 4

Example - 3:
#

Returns the minimum

System.out.printf("Min: %d\n", IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).distinct().min().getAsInt());
Min: 1

Example - 4:
#

Run through the list and print distinct items

IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).distinct().forEach(
x -> 
System.out.printf("%d ", x));
1 2 3 4

Example - 5:
#

Average of the distinct items

System.out.printf("Average (Distinct): %f\n", IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).distinct().average().getAsDouble());
Average (Distinct): 2.500000

Example - 6:
#

Different way of getting the count of elements.

System.out.printf(" Number of elements : %d\n", IntStream.of(a).asLongStream().count());
Number of elements : 12

Example - 7:
#

IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).forEach(x -> System.out.printf("%d ", x));

Get the list of elements

1 1 1 2 2 2 3 3 3 4 4 4

Example - 8:
#

System.out.printf("Average (All): %f\n", IntStream.range(0, a.length).map(i -> Integer.valueOf(a[i])).average().getAsDouble());
Average (All): 2.500000

Example - 9:
#

List<Integer> listOfIntegers = IntStream.of(a).boxed().collect(Collectors.toList());
System.out.println(listOfIntegers.toString());
[1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4]

Example - 10:
#

System.out.println(IntStream.range(0, a.length).map(i -> a[i]).boxed().collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).toString());

Creates a map of the value and the number of times it repeats

1=3, 2=3, 3=3, 4=3}

Example - 11:
#

Map<Integer, Long> valueMap = listOfIntegers.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        System.out.println(valueMap.toString());

Using list that we had in Example - 9 to get the map.

{1=3, 2=3, 3=3, 4=3}

Example - 12:
#

Returns the list of index for each value

System.out.println(IntStream.range(0, a.length).boxed().collect(Collectors.groupingBy( i -> a[Integer.valueOf(i)], Collectors.toList())));
{1=[0, 1, 2], 2=[3, 4, 5], 3=[6, 7, 8], 4=[9, 10, 11]}
Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Nth Prime

·2 mins
Prime number is an age old problem. I am trying to solve it via streams. class PrimeCalculator { public int nth(int nth) { if (nth <= 0) throw new IllegalArgumentException(); // Will skip the nth - 1 // 2 to n-1 return IntStream.iterate(2, i -> i + 1).filter(PrimeCalculator::isPrime).skip(nth - 1).findFirst().getAsInt(); } public static boolean isPrime(int x) { // till half of x return IntStream.rangeClosed(2, (int) (x/2) ).dropWhile(i -> x % i != 0).findFirst().isEmpty(); } } Explanation # public int nth(int nth) { if (nth <= 0) throw new IllegalArgumentException(); // Will skip the nth - 1 // 2 to n-1 return IntStream.iterate(2, i -> i + 1).filter(PrimeCalculator::isPrime).skip(nth - 1).findFirst().getAsInt(); } The method nth(int) allows you to return the nth prime starting at 2, 3, 5....

JavaStream: Characters

·1 min
Continuing from the last blog how about checking a pangram using streams. public class PangramChecker { private String allChars = "abcdefghijklmnopqrstuvwxyz"; public boolean isPangram(String input) { if (input.length() <= 0 || input.isBlank()){ return false; } return (allChars.chars().map(x -> (char) x).filter(x -> input.toLowerCase().indexOf(x) >= 0).count() == 26); } } All the for loops have been squeezed into a simple line

Java Streams

·2 mins
Stream is an new abstraction that lets one process data in a declarative way. A stream does not store data and, in that sense, is not a data structure. It also never modifies the underlying data source. The easiest way to learn a new API or a construct is by trying it. So here is an exercise that I tried to learn the Stream API. This is an exercise from exercism.io.