![]() |
VOOZH | about |
A lambda expression is a short code block that accepts parameters and outputs a result. Similar to methods, lambda expressions can be used directly within the body of a method and do not require a name. Converting a List of Lists to a HashSet is one typical situation. Java 8 introduces a feature called Lambda Expressions, which can be used elegantly to accomplish this change.
In this article, we will learn How to Convert a List of Lists to HashSet in Java Using Lambda Expression in Java.
There are certain methods to implement List if lists to HashSet using Lambda Expression mentioned below:
By flattening the nested lists and gathering the elements into a HashSet, we can use Lambda Expressions in Java to transform a List of Lists to a HashSet.
Result HashSet: [50, 20, 70, 10, 90, 60, 30]
In the above program,
list, where each inner list contains integers.flatMap operation.flatMap operation flattens the nested lists into a single stream of elements.collect(Collectors.toSet()) terminal operation.res.We first build a HashSet, and then we loop over each inner list using the forEach method on the outer list. The addAll() method is used inside the lambda expression to add every element from the inner list to the HashSet.
Result HashSet: [80, 50, 20, 70, 40, 10, 90, 60, 30]
In the above program,
list, where each inner list contains integers.forEach to iterate over each inner list (innerList) in the list.res using addAll().res.