Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Monday, January 22, 2018

Arrays.stream in java


We are having few methods by which we can directly get result using Arrays.stream


average()
max()
min()
sum()
findFirst()
findAny()
reduce((x,y)->x+y)
getAsInt() : convert value in Int
getAsDouble() : convert value in Double
Arrays.stream(arr_sample1)
            .asLongStream()

            .forEach(e->System.out.print(e + " "));


Arrays.stream(arr_sample1).findAny().getAsInt()

IntPredicate predicate = e->e % 11 == 0;
        System.out.println(Arrays.stream(arr_sample2).anyMatch(predicate));

Arrays.stream(arr_sample4) .allMatch(e->e % 2 == 0)

Arrays.stream(arr_sample4).noneMatch(e->e % 2 == 0)


Example:

public static void main(String[] args)
{
int arr_sample1[] = { 11, 2, 3, 6 };

// average()
// This method returns a average of an array
System.out.println("Example of average() : ");
System.out.println((Arrays.stream(arr_sample1)
.average()));

// findAny()
// It can return any value from the stream
// Most of the time it returns the first value 
// but it is not assured it can return any value
System.out.println("Example of findAny() : ");
System.out.println(Arrays.stream(arr_sample1)
.findAny());

// findFirst()
// It returns the first element of the stream
System.out.println("Example of findFirst() :");
System.out.println(Arrays.stream(arr_sample1)
.findFirst());

// max()
// It returns the max element in an array
System.out.println("Example of max() :");
System.out.println(Arrays.stream(arr_sample1)
.max());

// min()
// It returns the max element in an array
System.out.println("Example of max() :");
System.out.println(Arrays.stream(arr_sample1)
.min());

// reduce()
// It reduces the array by certain operation
// Here it performs addition of array elements
System.out.println("Example of reduce() :");
System.out.println(Arrays.stream(arr_sample1)
.reduce((x, y)->x - y));

// reduce() have another variation which we will
// see in different example
}




0 Comments:

Post a Comment

Stats