use of lambda and streams on nested object

use of lambda and streams on nested object

Content Index :

use of lambda and streams on nested object
Tag : java , By : user134570
Date : December 01 2020, 04:47 PM

it fixes the issue A mixed approach with a for loop iteration of the collection of Employees and streaming over the assets per employee and then filtering and mapping based on the condition and to item ids respectively.
List<String> assetItemIds = new ArrayList<>();
for (Employee employee : employees) {
            .flatMap(asset -> asset.getAssetItem().stream())
            .filter(assetItem -> assetItem.getOwnerShip().getStartDate() >= employee.getJoiningDate())
List<String> assetItemIds = employees.stream()
        .map(emp -> new AbstractMap.SimpleEntry<>(emp,
                        .flatMap(asset -> asset.getAssetItem().stream())
                        .filter(assetItem -> assetItem.getOwnerShip().getStartDate() >= emp.getJoiningDate())))
        .flatMap(e -> e.getValue().map(AssetItem::getId))

No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

How to iterate nested lists with lambda streams?

Tag : java , By : Allen
Date : March 29 2020, 07:55 AM
Hope this helps I am afraid that using streams and lambdas, your performance may suffer. Your current solution returns the first valid and parse-able node, however it is not possible to interrupt an operation on stream such as for-each (source).
Also, because you can have two different outputs (returned result or thrown exception), it won't be possible to do this with single line expression.
public static Result match(Response rsp) throws Exception {
    Map<Boolean, List<Object>> collect = rsp.getFirstNodes().stream()
            .flatMap(firstNode -> firstNode.getSndNodes().stream()) // create stream of SndNodes
            .filter(SndNode::isValid) // filter so we only have valid nodes
            .map(node -> {
                // try to parse each node and return either the result or the exception
                try {
                    return parse(node);
                } catch (ParseException e) {
                    return e;
            }) // at this point we have stream of objects which may be either Result or ParseException
            .collect(Collectors.partitioningBy(o -> o instanceof Result)); // split the stream into two lists - one containing Results, the other containing ParseExceptions

    if (!collect.get(true).isEmpty()) {
        return (Result) collect.get(true).get(0);
    if (!collect.get(false).isEmpty()) {
        throw (Exception) collect.get(false).get(0); // throws first exception instead of last!
    return null;
private static class IntermediateResult {

    private final SndNode node;
    private final Result result;
    private final List<ParseException> exceptions;

    private IntermediateResult(SndNode node, Result result, List<ParseException> exceptions) {
        this.node = node;
        this.result = result;
        this.exceptions = exceptions;

    private Result getResult() throws ParseException {
        if (result != null) {
            return result;
        if (exceptions.isEmpty()) {
            return null;
        // this will show all ParseExceptions instead of just last one
        ParseException exception = new ParseException(String.format("None of %s valid nodes could be parsed", exceptions.size()));
        throw exception;


public static Result match(Response rsp) throws Exception {
    return Stream.concat(
                    Arrays.stream(new SndNode[] {null}), // adding null at the beginning of the stream to get an empty "aggregatedResult" at the beginning of the stream
                            .flatMap(firstNode -> firstNode.getSndNodes().stream())
            .map(node -> new IntermediateResult(node, null, Collections.<ParseException>emptyList()))
            .reduce((aggregatedResult, next) -> {
                if (aggregatedResult.result != null) {
                    return aggregatedResult;

                try {
                    return new IntermediateResult(null, parse(next.node), null);
                } catch (ParseException e) {
                    List<ParseException> exceptions = new ArrayList<>(aggregatedResult.exceptions);
                    return new IntermediateResult(null, null, Collections.unmodifiableList(exceptions));
            .get() // aggregatedResult after going through the whole stream, there will always be at least one because we added one at the beginning
            .getResult(); // return Result, null (if no valid nodes) or throw ParseException
private static class ParsedNode {
    private final Result result;

    private ParsedNode(Result result) {
        this.result = result;

public static Result match(Response rsp) throws Exception {
    return rsp.getFirstNodes().stream()
            .flatMap(firstNode -> firstNode.getSndNodes().stream())
            .map(node -> {
                try {
                    // will parse all nodes because of flatMap
                    return new ParsedNode(parse(node));
                } catch (ParseException e ) {
                    return new ParsedNode(null);
            .filter(parsedNode -> parsedNode.result != null)
            .findFirst().orElse(new ParsedNode(null)).result;

How to convert List<Object[]> to Map<String,BigInteger> with Streams & Lambda Java8

Tag : java , By : Pitmairen
Date : March 29 2020, 07:55 AM
I hope this helps you . I have the data as:
Map<String, BigInteger> map =
                o -> (String) o[0],
                o -> (BigInteger) o[1],
                (b1, b2) -> b2

How to filter nested streams in Java 8 with lambda productions

Tag : java , By : Frank
Date : March 29 2020, 07:55 AM
around this issue You can use allMatch(predicate) to determine if all deals of an option are red:
List<Deal> output =
      .filter(d -> d.getDealop().stream().allMatch(po -> po.getColor().equals("red")))

How can i loop trough nested objects and validate some calculations with lambda and streams

Tag : java , By : Blight
Date : March 29 2020, 07:55 AM
around this issue Use Stream.of to create Category stream and then filter objects with rootCategory is not null
int sum = Stream.of(obj1, obj2, obj3)
        .filter(o -> Objects.nonNull(o.getRootCategory()))
        .mapToInt(c -> c.getQty() * c.getPrice())

Using streams and lambda expressions to replace a nested for loop to enter into a nested list

Tag : java , By : Star Gryphon
Date : March 29 2020, 07:55 AM
it helps some times Instead of directly translating your for loops to forEach, look at what your for loops are doing on a higher level of abstraction. They are transforming each element of your lists to another element. Whenever you see transformations like this, map is what you should call.
List<List<GrayscalePixel>> grayscalePhoto = 
    photo.stream().map(x ->
Related Posts Related QUESTIONS :
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • Combining or and negation in Java regex?
  • Unable to instantiate default tuplizer Exception
  • Multi-tenant migration to work with quarkus
  • Ignite persisting a Set: Cannot find metadata for object with compact footer
  • Maven cannot resolve Jacob dependency using eclipse
  • testcontainers oracle database container starts before database user is created
  • Launching two spring boot apps in integration test
  • Is there a way to add a HashMap's value that is a integer array into a ArrayList?
  • Is there any way that I can get a parameter in paintComponent?
  • Empty stack with one recursive method and one iterative method
  • What's the behavior of onBackpressureBuffer in RxJava2
  • Java regex can only use 1 quantifier in a lookback (need 2)
  • How to fix error in native query : it is showing syntax error near or at
  • How to retrieve nested object from a document and display it in FirestoreRecyclerOptions?
  • Why not use ListIterator for full LinkedList Operation?
  • Android Webview EvaluateJavascript sometimes does not return a response
  • Matcher java doesn't work but regex seems to be good
  • Finding dimensions of a .gif file
  • Java Number format how to change +/- sign to custom text
  • Entity partially saved when using JOINED inheritance strategy and setting spring.jpa.properties.hibernate.jdbc.batch_siz
  • Stored Procedure in Java Spring Boot Project returns null as Output
  • How to solve org.hibernate.MappingException which is causing due to inheriting a class
  • Clean Archtecture. Understanding of scheme
  • Processing 3 triangle not showing in Javafx 8 Window tab
  • How to specify a sequence-based generated value in Hibernate 5 via legacy mapping
  • Spring-boot application not getting auto-deployed on startup
  • How to only pass strings that the user select
  • Is there a way to SELECT using "GREATEST(field1, field2)" where field1 and field2 are aggregate sums in the sa
  • How to handle JSON objects wrapped into one JSON object with retrofit2?
  • Configure Hazelcast CPSubsystem Retries Timeout
  • how to use onBindViewHolder with multiple items in android RecyclerView
  • No ParameterResolver registered for parameter in BeforeAll method
  • Finding the path in a graph with the least casualties according to the lanchester square law
  • MongoWriteException when inserting into Mongodb with composite custom _id
  • Fetch Oracle procedure metadata with Java when multiple procedure signatures
  • Value modification of key-pair in HashMap and impact for a HashCode
  • Migration from solrj to spring-data-solr
  • How to check if you're still connected to the database with jpa
  • Use Date type in the graphql scheme
  • Split and add the string based on length
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com