简体   繁体   中英

Java 8 stream, groupBy and method invocation

I have the following code:

ConcurrentMap<String, Zipper> zippers = list.parallelStream()
    .map( f -> {return new Facet( f ) ; } )
    .collect( 
        Collectors.groupingByConcurrent( Facet::getZip,
        Collector.of( Zipper::new, 
                  Zipper::accept, 
                  (a,b)-> {a.combine(b); return a; } )
        )) ;

for ( String key: zippers.keySet() )
{
    zippers.get( key ).zip() ;
}

Given that I only need the Zipper objects to invoke the zip() method on them, is there a way to invoke this method as part of the stream just after the creation of each object (and to have these objects thrown away immediately after the zip() method has been invoked on them) rather than first having to create a map?

You probably want the 4-argument Collector#of which uses a finisher.

Note that f -> {return new Facet(f); } f -> {return new Facet(f); } can be written as Facet::new

ConcurrentMap<String, Zipper> zippers = list.parallelStream()
    .map(Facet::new)
    .collect( 
        Collectors.groupingByConcurrent(
            Facet::getZip,
            Collector.of( Zipper::new, 
                Zipper::accept, 
                (a,b)-> {a.combine(b); return a; },
                z -> {z.zip(); return z;}
            )
        )
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM