Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
13 views

Java 8

New java features with example

Uploaded by

abdulrcr334
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Java 8

New java features with example

Uploaded by

abdulrcr334
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Java 8

ie
ch
Te
Lets understand how we implement java functions without java8
features.
g
rin

Before Java 8: Used loops and manual iteration on arrays and


lists.
Sp
Before Java 8: Used java.util.Date and java.util.Calendar.

ie
ch
Te
Before Java 8: we use !=null for checking values.
g
rin
Sp
Before Java 8: Before java8 we don't have default methods in
java.Used abstract classes or implemented methods in all classes.

ie
ch
Before Java 8, coding was more complicated and required more lines
Te
of code, which made it harder to read and prone to errors.
So to avoid this repeated lines of coding and to make code more
readable and reliable java people introduced some additional features
in java8(jdk8) version.
g
Java 8 was introduced in 2014, which made a significant impact on the
way of writing code in java.
rin

As of now, Java 11 and Java 17 are among the most widely used
versions, with Java 8 still being popular in many legacy systems.
Sp

Java 8 brought several improvements:

1. Lambda Expressions: Allow functional programming, enabling


you to treat functionality as a method argument or code as data.
This leads to more readable and concise code.
2. Stream API: Provides a powerful way to process sequences of
elements. It supports operations like filtering, mapping, and
reducing, making it easier to work with collections.

ie
3. New Date and Time API: Replaces the old Date and Calendar
classes with a more intuitive and comprehensive API (java.time

ch
package), improving date and time handling.

Te
4. Optional Class: Introduced to handle nullable values gracefully,
reducing NullPointerException risks.
g
rin

5. Default Methods: Allows interfaces to have method


Sp

implementations, which provides flexibility in evolving interfaces


without breaking existing implementations.
6. Enhanced JavaScript Integration: Through Nashorn, a new
JavaScript engine.

7. Functional Interface: In java8 we have functional interface


which means an interface which has only one abstract method.

ie
ch
Te
g
Now let's dive in depth on each feature.
rin

1.Functional Interfaces:

Functional interfaces were introduced as part of Java 8.


Sp

Functional interfaces are interfaces that have exactly one abstract


method.

Functional interfaces are annotated with @FunctionalInterface.


This annotation is used to explicitly indicate that an interface is
intended to be a functional interface, meaning it should have
exactly one abstract method.
Use of Functional interfaces is used to enable functional
programming and support lambda expressions & enabling
higher-order functions.

Is it mandatory to annotate with @FunctionalInterface?

No, it’s not mandatory to annotate with @FunctionalInterface,


but it's recommended. This annotation serves as documentation

ie
and helps the compiler ensure that the interface adheres to the
functional interface requirements (only one abstract method).

ch
Some key points to remember while creating
@FunctionalInterface Te
If you mark any Interface with @FunctionalInterface then you
must create only one abstract method inside it and any number
of default methods.
g
1.A FunctionalInterface can extend a regular interface that does
not have any abstract methods but it may contain default
rin

methods.
Sp
2.A FunctionalInterface can extend a regular interface
that does have one abstract method but the functional
interface should not contain any abstract method.

ie
ch
Te
3. We can extend a functional interface in java.
g
rin
Sp
How to implement functional interfaces.
To implement functional interfaces in Java, you can use lambda
expressions, method references, or traditional anonymous classes.

Now let's understand lambda expressions before implementing the


functional interfaces…

Using Lambda expression: is a powerful feature in

ie
Java 8 that allows you to implement the functional interfaces.
They make your code more readable and expressive, especially

ch
when working with collections, streams, and functional
programming constructs.

@FunctionalInterface
interface MyInterface {
Te
void myAbstractMethod();
}

Lets look the implementation of above functional interface with


g
lambda expression:
rin

// Java 8: Using lambda expression


public class Java8Example {
public static void main(String[] args) {
MyInterface implementation = () -> {
Sp

System.out.println("Hello from
myAbstractMethod!");
};

implementation.myAbstractMethod();
// Call the implemented method
}
}
How to write a lambda expression for a functional interface…

Syntax:

● Parameters: Specified in parentheses, e.g., (x, y).


● Arrow Token: -> separates parameters from the body.
● Body: Can be a single expression or a block of statements.

ie
1.If method has two arguments and has to compute some
operation on variables in one line then you have to use () for

ch
arguments and no need of {} for method body.

2.If method has one argument and has to some compute some
operation on variable in one line then you don’t need to use () for
Te
arguments and no need of {} for method body.

3.If method has two arguments and has to compute some


operation on variables in multiple statements(in body) then you
have to use () for arguments and need of {} for method body.
g
rin
Sp
Method Reference:
● Method references in Java 8 provide a concise way to refer
to methods or constructors of classes, especially when
working with functional interfaces.
● Each time when you are using a lambda expression to just
refer to a method, you can replace your lambda expression
with a method reference.

ie
There are four main types of method references in Java 8:
1. Reference to a Static Method
2. Reference to an Instance Method of a Particular Object

ch
3. Reference to an Instance Method of an Arbitrary Object of a
Particular Type
4. Reference to a Constructor
Te
Example: Here I am taking an example for static method
reference and will explain how we are converting the lambda
expression into method reference.
g
Lambda Expression:
rin

Function<Integer, String> intToStringLambda = (x) ->


Integer.toString(x);
String result = intToStringLambda.apply(123);
Sp

Equivalent Method Reference (Static Method):

Function<Integer, String> intToString = Integer::toString;


String result = intToString.apply(123);
Some important Functional Interfaces in java.

Java 8 has some inbuilt functional interfaces that are heavily


implemented by lambda expressions and used with stream APIs.
These functional interfaces are defined in the java.util.function
package.
1. Supplier<T>:

ie
● Abstract method: T get()
● This represents a supplier of results, providing a value
without taking any input.

ch
● It is commonly used for lazy initialization or generating
values.
Example: Te
Supplier<Integer> randomNumberSupplier = () -> (int)
(Math.random() * 100);
int randomValue = randomNumberSupplier.get();
//Generates a random integer between 0 and 99
g
2. Consumer<T>:
● Abstract method: void accept(T t)
rin

● This represents an operation that accepts a single input and


returns no value or result.
● It is used for performing actions on input values, such as
printing, saving, or processing.
Sp

Example:
Consumer<String> printMessage = message ->
System.out.println(message);
printMessage.accept("Hello, World!"); // Prints "Hello,
World!"
3. Function<T, R>:
● Abstract method: R apply(T t)
● This represents a function that accepts one argument and
produces a result.
● It is commonly used for mapping or transforming input to
output.
Example:
Function<Integer, String> intToString = num -> "Number: " +

ie
num;
String result = intToString.apply(42); // "Number: 42"

ch
4. Predicate<T>:
● Abstract method: boolean test(T t)
● It represents a predicate/condition, a boolean-valued
function that checks a condition on an input.
Te
● It is used for filtering or testing elements based on a
condition.
Example:
Predicate<Integer> isEven = num -> num % 2 == 0;
g
boolean result = isEven.test(8); // true
rin

5. UnaryOperator<T>:
● Abstract method: T apply(T t)
● This is a special case of the Function interface where the
input and output types are the same.
Sp

● It is used for operations that transform an input into an


output of the same type.
Example:
UnaryOperator<Integer> square = num -> num * num;
int result = square.apply(5); // 25
6. BinaryOperator:
● Abstract method: T apply(T t, T u)
● It is a special case of the BiFunction interface where the two
input arguments and the output are of the same type.
● It is used for binary operations that combine two inputs into
a single result.
Example:
BinaryOperator<Integer> add = (a, b) -> a + b;

ie
int result = add.apply(3, 7); // 10

ch
7. Runnable:

● Represents a task that can be executed without returning a


result. Te
● Method: void run();

Runnable task = () -> System.out.println("Task is running");

new Thread(task).start();
g
rin

8.Comparator<T>

● Represents a comparison function that compares two


objects.
Sp

● Method: int compare(T o1, T o2)

Comparator<String> lengthComparator = (s1, s2) -> s1.length() -


s2.length();

List<String> names = Arrays.asList("John", "Jane", "Doe");

names.sort(lengthComparator);
2.Stream API:
The Java Stream API, introduced in Java 8, provides a powerful
way to process sequences of elements, making it easier to work
with collections and arrays in a functional style.

Stream means a flow. In java stream applies on collections.

● Streams process elements in a pipeline manner. Each

ie
element flows through the sequence of operations.

Let's take one realtime example:

ch
Consider a water tank(List) on top of your home, we will
connect that water tank through a series of
pipes(intermediate methods) to our sink and at the end of
Te
the pipe we keep a tap(terminal methods) to control water
flow.

In the same way stream api is designed , when we apply


g
stream on collections it will start applying some operation on
each element such as filtering and multiplying as in the
rin

same way we will heat the water through geyser before


water down to bucket.

But here point be noted , without opening tap water can't


come down to the bucket , as in the same way if we apply
Sp

terminal methods on stream then only intermediate


methods will start doing operation.

What are intermediate methods & terminal methods ?


Intermediate Methods:

● Transform a stream into another stream. They are lazy,


meaning they do not process the data until a terminal
operation is called.

Characteristics:

● Always return a new stream.

ie
● Can be chained together.
● Operations are not executed immediately.

ch
● filter(Predicate<T> predicate): Filters elements based on
a condition.
Te
● map(Function<T, R> mapper): Transforms elements

using a function.
g
● distinct(): Removes duplicate elements.
rin

● sorted(): Sorts elements.

● limit(long maxSize): Limits the number of elements in the


Sp

stream.

● skip(long n): Skips the first n elements in the stream.

Terminal Methods:
● Produce a result or a side effect. They trigger the execution
of intermediate operations.

Characteristics:

● Consume the stream.


● Return a concrete value or collection.

ie
● forEach(Consumer<T> action): Performs an action for each
element.
● collect(Collector<T, A, R> collector): Collects elements into a

ch
collection.
● reduce(T identity, BinaryOperator<T> accumulator):
Aggregates elements into a single value.
● count(): Counts the number of elements.
Te
● anyMatch(Predicate<T> predicate): Checks if any element
matches a condition.
● allMatch(Predicate<T> predicate): Checks if all elements
match a condition.
g
● noneMatch(Predicate<T> predicate): Checks if no elements
match a condition.
rin
Sp

Example Workflow: The below examples convert names list to


stream and then start filter the names which starts with “J” and
then convert to each filtered value to uppercase, the it will sort
the values and finally collects into the list.

Note: Without applying terminal operator stream api doesn't start


processing.

We will have more coding questions at the end of the pdf.

ie
ch
Te
g
rin
Sp
New Date and Time API:

The new Date and Time API, introduced in Java 8 (java.time


package), addresses many of the problems of the old
java.util.Date and java.util.Calendar.

These are the useful introduced in date & time api.

ie
ch
Advantages: Te
● Immutable: Instances are immutable, enhancing thread
safety.
● Fluent API: Methods support method chaining.
● Comprehensive: Includes classes for various use cases
g
(e.g., Period, Duration).
● Time Zones: Better handling of time zones and offsets.
rin
Sp
Optional Class:

The Optional class in Java is a container object which may or may


not contain a non-null value. It is used to avoid
NullPointerException and to express the absence of a value more
clearly.

ie
How to Create an Optional:

1.Empty Optional: Creates an Optional that contains no value.

ch
Useful for methods that explicitly return an empty result.

Optional<String> empty = Optional.empty();


Te
2.Optional with a Value: Creates an Optional with the given
non-null value. Throws NullPointerException if the value is null.
Use this when you are sure the value is present.

Optional<String> nonEmpty = Optional.of("Hello");


g

3.Optional with a Nullable Value: Creates an Optional that


rin

may or may not contain a value. If the argument is null, it returns


an empty Optional. This is useful when the value could be null,
allowing safe handling without explicit null checks.
Sp

Optional<String> nullable = Optional.ofNullable(null);


Key Methods of Optional:

1.isPresent:
● Checks if a value is present.

if (optional.isPresent()) {
System.out.println(optional.get());
}

ie
2.ifPresent:
● Executes a lambda expression if a value is present.

ch
optional.ifPresent(value -> System.out.println(value));

3.orElse:
● Returns the value if present; otherwise, returns a default
Te
value.

String result = optional.orElse("Default");

4.orElseGet:
g
● Returns the value if present;
● otherwise, calls a supplier function to provide a value.
rin

String result = optional.orElseGet(() -> "Default");

5.orElseThrow:
● Returns the value if present;
Sp

● otherwise, throws an exception.

String result = optional.orElseThrow(() -> new


IllegalArgumentException("Value not present"));

6.get:
● Returns the value if present;
● throws NoSuchElementException if not.

String value = optional.get();


When to Use Optional

● Method Return Types: Use Optional as a return type when a


method might not return a value.
● Avoid Null Checks: Replace traditional null checks with
Optional to make code more readable.
● Express Intent: Clearly express that a variable might not
have a value.

ie
Advantages of Using Optional

● Null Safety: Reduces the risk of NullPointerException.

ch
● Readability: Makes the code more readable and expresses
intent clearly.
● Functional Programming: Integrates well with Java's
Te
functional programming features, such as streams and
lambda expressions.
g

Stream methods:
rin

filter: Used to filter elements based on a condition.


Sp

list.stream().filter(s -> s.length() > 3);

map: Transforms each element to another form.

list.stream().map(String::length);
sorted: Sorts the elements of the stream.

list.stream().sorted();

collect: Collects the elements into a collection, such as a list.

list.stream().collect(Collectors.toList());

ie
forEach: Performs an action for each element.

ch
list.stream().forEach(System.out::println);
Te
distinct: Removes duplicate elements.

list.stream().distinct();
g

limit: Limits the number of elements to a specified number.


rin

list.stream().limit(5);
Sp

skip: Skips the first N elements.

list.stream().skip(3);

reduce: Combines elements to produce a single result.

list.stream().reduce("", String::concat);
count: Counts the number of elements in the stream.

list.stream().count();

findFirst: Finds the first element in the stream.

ie
list.stream().findFirst();

ch
findAny: Finds any element in the stream.

list.stream().findAny();
Te
anyMatch: Checks if any elements match a given condition.
g

list.stream().anyMatch(s -> s.length() > 3);


rin

allMatch: Checks if all elements match a given condition.


Sp

list.stream().allMatch(s -> s.length() > 3);

noneMatch: Checks if no elements match a given condition.

list.stream().noneMatch(s -> s.length() > 3);


max: Finds the maximum element based on a comparator.

list.stream().max(Comparator.naturalOrder());

min: Finds the minimum element based on a comparator.

list.stream().min(Comparator.naturalOrder());

ie
ch
Te
g
rin
Sp
Following are some of the famously asked Java8 Interview
Questions.

1.Print Even nos from the list?


int arr[] = new int[]{9,10,15,8,49,25,98,32,10};

ie
Arrays.stream(arr).filter(i->i%2==0).forEach(System.out::println);

ch
2. Find First element in the list?
int arr[] = new int[]{9,10,15,8,49,25,98,32,10};
Te
Arrays.stream(arr).findFirst().ifPresent(System.out::println);
g
3. Find duplicates in the list?
rin

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

Arrays.stream(arr).filter(s->!set.add(s)).forEach(System.out::println);
Sp

4. Print nos that start with 1 from the list ?


Arrays.stream(arr).mapToObj(s->s+"").filter(s->s.startsWith("1")).

forEach(System.out::println);

5. Find minimum and maximum in the list ?


System.out.println("Max in array"+Arrays.stream(arr).max().getAsInt());

System.out.println("Min in array"+Arrays.stream(arr).min().getAsInt());
6. Find first non repeated character ?
String input = "swiss";

// First pass: collect character counts

Map<Character, Long> charCountMap = input.chars()

.mapToObj(c -> (char) c)

.collect(Collectors.groupingBy(c -> c, HashMap::new,

ie
Collectors.counting()));

ch
// Second pass: find the first character with count 1

Optional<Character> firstNonRepeatedChar = input.chars()

.mapToObj(c -> (char) c)


Te
.filter(c -> charCountMap.get(c) == 1)

.findFirst();

firstNonRepeatedChar.ifPresentOrElse(
g
c -> System.out.println("First non-repeated character: " + c),

() -> System.out.println("No non-repeated character found")


rin

);
Sp

7. Sort the elements in asc and desc ?


Arrays.stream(arr).sorted().forEach(System.out::println);

Arrays.stream(arr).boxed().sorted(Collections.reverseOrder())

.forEach(System.out::println);
8. Perform cube on list elements and filter numbers greater than
50 ?
list.stream().map(i->i*i*i).filter(i->i>50).

collect(Collectors.toList()).forEach(System.out::println);

9. To sort an array and then convert the sorted array into Stream

ie
Arrays.parallelSort(arr);

Arrays.stream(arr).forEach(System.out::println);

ch
10. Find unique nos from the list ?
List list= Arrays.asList(11,22,33,44,11,22);
Te
System.out.println(list.stream()

.filter(x-> Collections.frequency(list,x)==1)

.collect(Collectors.toList()));
g
11. Optional Field usage ?
rin

class Nodes{

int id;

String tagName;
Sp

int count;

Nodes(int id,String tagName,int count){

this.id=id;

this.tagName=tagName;

this.count=count;

public int getId() {


return id;

public void setId(int id) {

this.id = id;

ie
public String getTagName() {

return tagName;

ch
public void setTagName(String tagName) {

this.tagName = tagName; Te
}

public int getCount() {

return count;
g
}
rin

public void setCount(int count) {

this.count = count;

}
Sp

Nodes node1=new Nodes(1,"vee",1);

Nodes node2=new Nodes(2,"viv",2);

List<Nodes> nodesList=new ArrayList<>();

nodesList.add(node1);

nodesList.add(node2);

Optional.ofNullable(nodesList).
orElseGet(Collections::emptyList).

stream().filter(Objects::nonNull).

map(Nodes::getTagName).forEach(s->System.out.println("tag names
is:"+s));

12 . To find only duplicate elements from the String ArrayList ?

ie
List<String> list1 = Arrays.asList("abc", "def", "xyz", "mno", "pqr",

"def", "xyz", "stu");

Set<String> set1=new LinkedHashSet<>();

ch
list1.stream().filter(s->set1.add(s)).forEach(System.out::println);

13. To print the count of each character in a String ?


Te
String s = "string data to count each character";

Map<String, Long> countMap = Arrays.stream(s.split(""))

.map(String::toLowerCase)
g
.collect(Collectors.groupingBy(str -> str, HashMap::new,
Collectors.counting()));
rin

System.out.println(countMap);
Sp

14 . Print odd and Even list ?


int[] arr1= new int[]{1,2,4,6,7};

System.out.println(Arrays.stream(arr1).

mapToObj(ob -> Integer.valueOf(ob)).

collect(Collectors.groupingBy(t-> t%2 == 0 ?"ODD" : "EVEN")));


15. Print odd , Even sum?
Map<String, Integer> map1 = Arrays.stream(arr1).boxed().

collect(Collectors.groupingBy(e -> e % 2 == 0 ? "OddSum" : "EvenSum",

Collectors.summingInt(Integer::intValue)));

System.out.println("map::"+map1);

ie
16. Convert list to map
class Person{

ch
int id;

String name;

Person(int id,String name){

this.id=id;

this.name=name;
Te
}
g
public int getId() {

return id;
rin

public void setId(int id) {


Sp

this.id = id;

public String getName() {

return name;

}
public void setName(String name) {

this.name = name;

List<Person> listPerson = new ArrayList<>();

listPerson.add(new Person(1,"vna"));

listPerson.add(new Person(2,"vid"));

ie
Map<Integer,Person1> mapPerson = listPerson.stream().

collect(Collectors.toMap(Person1::getId,Function.identity()));

ch
System.out.println(mapPerson);

17 . Find the count of words in a string?


String
Te
str = "this is word count for word is good";

Map<String,Long> mapStr=Arrays.stream(str.split(" ")).

filter(x->Collections.frequency(Arrays.asList(str.split(" ")),x)>=1).
g
collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,

Collectors.counting()));
rin

System.out.println(mapStr);

18. Print the word count in reverse order ?


Sp

Arrays.stream(str.split(" "))

.filter(x->Collections.frequency(Arrays.asList(str.split(" ")),x)>=1)

.collect(Collectors.groupingBy(Function.identity(),LinkedHashMap::new,Collector
s.counting())).entrySet().stream()

.sorted(Map.Entry.<String, Long> comparingByValue().reversed()

.thenComparing(Map.Entry.comparingByKey())).forEach(System.out::println);
19. Print Employee salary in Ascending order
class Employee{

private int id;

private String name;

private int age;

ie
private long salary;

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

super();

ch
this.id = id;

this.name = name;

this.age = age;

this.salary = salary;
Te
}

public int getId() {


g
return id;

}
rin

public void setId(int id) {

this.id = id;

}
Sp

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public int getAge() {

return age;
}

public void setAge(int age) {

this.age = age;

public long getSalary() {

return salary;

ie
public void setSalary(long salary) {

this.salary = salary;

ch
}

@Override

public String toString() {


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

}
g
List < Employee > employees = new ArrayList < Employee > ();

employees.add(new Employee(10, "Ramesh", 30, 400000));


rin

employees.add(new Employee(20, "John", 29, 350000));

employees.add(new Employee(30, "Tom", 30, 450000));

employees.add(new Employee(40, "Pramod", 29, 500000));


Sp

employees.add(new Employee(50, "Pramodini", 31, 500000));

List<Employee> resultAsc=employees.stream().

sorted(((o1, o2) -> (int)(o1.getSalary()- o2.getSalary()))).

collect(Collectors.toList());

System.out.println("Ascending order::"+resultAsc);

System.out.println(employees.stream().

sorted(Comparator.comparingLong(Employee::getSalary)).
collect(Collectors.toList()));

List<Employee> resultDesc=employees.stream().

sorted(((o1, o2) -> (int)(o2.getSalary()- o1.getSalary()))).

collect(Collectors.toList());

System.out.println("Descending order::"+resultDesc);

System.out.println(employees.stream().

ie
sorted(Comparator.comparingLong(Employee::getSalary).reversed()).

collect(Collectors.toList()));

ch
20 . Occurrence of elements ?
List<String> names = Arrays.asList("AA", "BB", "AA", "CC");
Te
HashMap<String,Long> map = names.stream().

collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new,

Collectors.counting()));
g
System.out.println(map);
rin

21.Process a list of numbers in parallel to compute their sum?


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Sp

int sumParallel = numbers.parallelStream()


.mapToInt(Integer::intValue)
.sum();

System.out.println("Sum using parallel stream: " + sumParallel);

22.Write a Java program to sort a list of objects based on multiple


name and salary?
Person(name="John", age=25, salary=5000)
Person(name="Jane", age=30, salary=6000)
Person(name="Bob", age=20, salary=4000)
persons.sort(Comparator.comparing(Person::getAge).thenComparing(Person::ge
tSalary));

23.Write a Java program to find the shortest string in a list.?


["hello", "world", "abc", "def"]

String shortestWord = words.stream()

ie
.min(Comparator.comparing(String::length)).get();
System.out.println(shortestWord);

ch
24.Write a Java program to group a list of objects by a specific
field?
Order(customer="John", amount=100)
Te
Order(customer="Jane", amount=200)
Order(customer="John", amount=300)

Map<String, List<Order>> customerOrders = orders.stream()


.collect(Collectors.groupingBy(Order::getCustomer));
g
System.out.println(customerOrders);
rin

25.Given a list of integers, write a Java 8 code snippet to find the


second highest number?
List<Integer> numbers = Arrays.asList(1, 3, 4, 5, 0, 2, 6, 7, 8, 9);
int secondHighest = numbers.stream()
.sorted(Comparator.reverseOrder())
Sp

.distinct()
.skip(1)
.findFirst()
.orElseThrow(NoSuchElementException::new);

26.Given a list of Optional<Integer>, write a Java 8 code


snippet to calculate the sum of all present integers. If all
Optional objects are empty, the result should be 0?
List<Optional<Integer>> optionals = Arrays.asList(
Optional.of(1),
Optional.empty(),
Optional.of(3),
Optional.of(5),
Optional.empty()
);

int sum = optionals.stream()


.filter(Optional::isPresent)
.mapToInt(Optional::get)
.sum();

ie
System.out.println("Sum: " + sum); // Output: Sum: 9

ch
27.Given a list of Optional<String>, write a Java 8 code snippet
to filter out the empty optionals and collect the values into a list?
List<Optional<String>> optionals = Arrays.asList(Optional.of("A"),
Optional.empty(), Optional.of("B"));
List<String> result = optionals.stream()
Te
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());

28.Given a list of lists of integers, write a Java 8 code snippet to


g
flatten it into a single list of integers?
List<Optional<String>> optionals = Arrays.asList(Optional.of("A"),
rin

Optional.empty(), Optional.of("B"));
List<String> result = optionals.stream()
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
29.Write a Java 8 code snippet to calculate the sum of the
Sp

squares of all elements in a list of integers?


List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sumOfSquares = numbers.stream()
.map(x -> x * x)
.reduce(0, Integer::sum);

30. Given a list of strings, write a Java 8 code snippet to


concatenate them into a single string separated by commas?
List<String> strings = Arrays.asList("apple", "banana", "cherry");
String result = strings.stream()
.collect(Collectors.joining(", "));

You might also like