0% found this document useful (0 votes)
14 views8 pages

Java 8 Stream Practice Exercises

The document contains Java 8 lab exercises demonstrating various Stream functions, including filtering, sorting, and mapping operations on lists of integers and employee objects. It also covers functional interfaces such as Consumer, Predicate, Function, and Supplier, providing examples of their usage. Additionally, it includes explanations of concepts like flatMap and demonstrates how to manipulate collections using Java 8 features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views8 pages

Java 8 Stream Practice Exercises

The document contains Java 8 lab exercises demonstrating various Stream functions, including filtering, sorting, and mapping operations on lists of integers and employee objects. It also covers functional interfaces such as Consumer, Predicate, Function, and Supplier, providing examples of their usage. Additionally, it includes explanations of concepts like flatMap and demonstrates how to manipulate collections using Java 8 features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java 8 Additional Practice Lab Exercises

package [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

class Employee {

int id;

String name;

int salary;

public Employee(int id, String name, int salary) {

super();

[Link] = id;

[Link] = name;
[Link] = salary;

@Override

public String toString() {

return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";

public class MyClass1 {

public static void main(String[] args) {

//1. Given a list of integers, find out all the even numbers that exist in the list using
Stream functions?

List<Integer> list = [Link](10, 10, 11, 12, 13, 14, 15, 22, 31, 11, 44);

List<Integer> evenList = [Link]().filter(x -> x % 2 == 0).collect([Link]());

[Link](evenList);

//2. Given a list of integers, find out all the numbers starting with 1 using Stream functions?

List<Integer> oneList = [Link]().filter(x ->


[Link](x).startsWith("1")).collect([Link]());

[Link](oneList);

//3. How to find duplicate elements in a given integers list in java using Stream functions?

List<Integer> duplicateList = [Link]().filter(x -> [Link](x) !=


[Link](x)).collect([Link]());
[Link](duplicateList);

Set<Integer> duplicateSet = [Link]().filter(x -> [Link](x) !=


[Link](x)).collect([Link]());

[Link](duplicateSet);

Set<Integer> tempSet = new HashSet<>();

long duplicateCount = [Link]().filter(x -> [Link](x) == false).count();

[Link](duplicateCount);

//4. Given the list of integers, find the first element of the list using Stream functions?

int firstElement = [Link]().findFirst().get();

[Link](firstElement);

//5. Given a list of integers, find the total number of elements present in the list using Stream
functions?

long count = [Link]().count();

[Link](count);

//6. Given a list of integers, find the maximum value element present in it using Stream
functions?

int max = [Link]().max((x,y) -> x - y).get();

[Link](max);

//7. Sort the Employee object using salary

List<Employee> empList = [Link](

new Employee(101, "Valan", 3000),


new Employee(102, "Lakshmipathi", 2000),

new Employee(103, "Priya", 4000)

);

List<Employee> sortList = [Link]().sorted((e1, e2) -> [Link] -


[Link]).collect([Link]());

[Link](sortList);

//8. Given a list of integers, sort all the values present in it using Stream functions?

List<Integer> sortList1 = [Link]().sorted().collect([Link]());

[Link](sortList1);

//9. Given a list of integers, sort all the values present in it in descending order using Stream
functions?

List<Integer> ascSort = [Link]().sorted((x,y) -> y - x).collect([Link]());

[Link](ascSort);

//10. Given an integer array nums, return true if any value appears at least twice in the array,
and return false if every element is distinct.

[Link]();

boolean flag = [Link]().filter(x -> [Link](x) == false).count() > 0 ? true : false ;

[Link](flag);

//11. Java 8 program to find factorial of given list of integer values

List<Integer> list1 = [Link](1, 2, 3, 4, 5);

List<Integer> factList = [Link]().map(x -> {

int fact = 1;

for(int i=1; i<=x;i++)


fact = fact * i;

return fact;

}).collect([Link]());

[Link](factList);

//12. Write a Java 8 program to sort an array and then convert the sorted array into Stream?

int arr[] = {3, 5, 2, 1, 7};

[Link](arr);

[Link](arr).forEach([Link]::println);

//13. Convert a List of String into upper case using stream

List<String> strList = [Link]("Apple", "Orange", "Grape");

List<String> upperList = [Link]().map(x -> [Link]()).collect([Link]());

[Link](upperList);

//14. Convert a List of String into a Map key and it's length as Map Value using Java 8 Stream

Map<String, Integer> map = [Link]().collect([Link](x -> x, x -> [Link]()));

[Link](map);

//15. flatMap

/*

* flatMap() V/s map():

map() transforms each element of a stream into another object, resulting in a


stream of the same size as the input. It’s used for one-to-one transformations.
It processes the stream of values.

flatMap() transforms each element of a stream into zero or more elements,


potentially changing the size of the stream. It’s used for one-to-many transformations and flattening
nested structures.

It processes the stream of stream's values.

*/

List<Integer> even = [Link](2, 4, 6, 8);

List<Integer> odd = [Link](1, 3, 5, 7, 9);

List<List<Integer>> evenOdd = [Link](even, odd);

[Link]("Before Flattering");

[Link](evenOdd);

List<Integer> result = [Link]().flatMap(x -> [Link]()).collect([Link]());

[Link]("After Flattering");

[Link](result);

/* Java 8's — Consumer, Predicate, Supplier, and Function */

//16. Java 8 : Consumer

/*

* A Consumer is an in-build functional interface in the [Link] package. we use


consumers when we need to consume objects, the consumer takes an input value and returns nothing.

*/

Consumer<String> consumer = str -> [Link](str);

[Link](consumer);

Consumer<Integer> evenConsumer = n -> {


if(n % 2 == 0)

[Link](n);

};

[Link](evenConsumer);

//17. Java 8 : Predicate

// A Predicate is a functional interface, which accepts an argument and returns

//a boolean. Usually, it is used to apply in a filter for a collection of objects.

Predicate<String> predicate = str -> [Link]("p");

[Link]().filter(predicate).forEach([Link]::println);

Predicate<Integer> evenPredicate = n -> n % 2 == 0;

[Link]().filter(evenPredicate).forEach([Link]::println);

//18. Java 8 : Function

//A Function is another in-build functional interface in [Link] package,

//the function takes an input value and returns a value. Mostly function used in map

//feature of stream APIs.

Function<String, Character> function = str -> [Link](0);

[Link]().map(function).forEach([Link]::println);

Function<Integer, String> function1 = n -> {

if (n % 2 == 0)

return "Even";

else
return "Odd";

};

[Link]().map(function1).forEach([Link]::println);

//19. Supplier

//The Supplier Interface is a part of the [Link] package. It represents a

//function that does not take in any argument but produces a value of type T.

Supplier<String[]> supplier = () -> new String[] {"One", "Two", "Three"};

[Link]([Link]()).forEach([Link]::println);

Predicate<String> myPredicate = str -> [Link]("o") || [Link]("O");

Function<String, Character> myFunction = str -> [Link](0);

Consumer<Character> myConsumer = c -> [Link](c);

[Link]([Link]()).stream().filter(myPredicate).map(myFunction).forEach(myConsumer);

Common questions

Powered by AI

To convert a list of strings into a Map in Java 8 where each string is associated with its length, use `Collectors.toMap` in conjunction with the `stream` API. For example: `strList.stream().collect(Collectors.toMap(x -> x, x -> x.length()))` creates a Map where keys are the strings and values are their respective lengths .

To sort an array of integers and convert it into a Stream, employ `Arrays.sort(arr)` to first sort the array, followed by `Arrays.stream(arr).forEach(System.out::println)` to convert the sorted array into a Stream for processing or output .

The `Consumer` interface accepts a single argument and performs an operation without returning any result, making it useful for operations like printing (`Consumer<String> consumer = str -> System.out.println(str)`). The `Predicate` interface takes an argument and returns a boolean, primarily used for filtering (`Predicate<Integer> evenPredicate = n -> n % 2 == 0`). The `Supplier` interface provides results without any input, useful for lazy initialization or deferred execution (`Supplier<String[]> supplier = () -> new String[] {"One", "Two", "Three"}`).

The `map` method is used to transform each element in a stream, which might change the element type, enabling one-to-one mapping such as converting strings to their uppercase forms. After transformation using `map`, `collect` is typically used to gather the results into a desired collection format, such as a list, set, or map (`Collectors.toList()`, `Collectors.toSet()`). For example, converting a string list to uppercase involves `strList.stream().map(x -> x.toUpperCase()).collect(Collectors.toList())` .

`Function` in Java 8 is used to apply transformations and return a result, usually seen in mapping operations, like transforming characters in a string list using `Function<String, Character> function = str -> str.charAt(0)`. `Predicate`, on the other hand, evaluates a condition and returns a boolean, and is typically used in filtering: `Predicate<String> predicate = str -> str.contains("p")`. Use `Function` for transformations where a result is expected and `Predicate` for conditional checks .

A list of integers can be processed using Java Streams to identify numbers starting with a particular digit by converting each number to a string and applying a filter. For instance, to find numbers starting with '1', use: `list.stream().filter(x -> String.valueOf(x).startsWith("1")).collect(Collectors.toList())`, which filters and collects numbers starting with the specified digit .

`flatMap` transformations involve each element being transformed into a stream, resulting in flattening of the elements into a single stream. This is ideal for merging multiple collections or dealing with nested collections, such as flattening lists of lists into a flat list (`evenOdd.stream().flatMap(x -> x.stream()).collect(Collectors.toList())`). Conversely, `map` maintains the structure of one input to one output and does not alter the nesting level, as seen in mapping strings to their lengths .

`map()` transforms each element of a stream into another object and results in a stream of the same size, hence used for one-to-one transformation. For example, converting a list of integers to their factorials. In contrast, `flatMap()` is used for one-to-many transformations, transforming each element into multiple resulting in flattening nested structures, such as combining lists into a single list. For instance, two lists of integers can be flattened using `evenOdd.stream().flatMap(x -> x.stream()).collect(Collectors.toList())` .

To sort a list of Employee objects by salary using Stream functions in Java 8, you can employ the `sorted` method with a comparator that compares employees based on their salary. For example: `empList.stream().sorted((e1, e2) -> e1.salary - e2.salary).collect(Collectors.toList())` sorts the `empList` in ascending order by salary .

To identify duplicate elements using Java Stream functions, you can utilize list indexing compared with last indices within a filter, i.e., `list.stream().filter(x -> list.indexOf(x) != list.lastIndexOf(x)).collect(Collectors.toList())`, which provides duplicates as a list. Alternatively, leveraging a `HashSet`, duplicates can be found using a condition `tempSet.add(x) == false` within a filter, which generally improves efficiency as it avoids multiple list traversals .

You might also like