Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use the Stream.mapMult of Java16

Shulou Source: shulou.com Published: 2022-06-01 11:47:54 10月01日 Update

This article mainly introduces the relevant knowledge of "how to use the Stream.mapMult of Java16". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this article "how to use the Stream.mapMult of Java16" can help you solve the problem.

The following example shows how to replace each string in the stream with uppercase and lowercase versions of mapMulti:

Stream.of ("Twix", "Snickers", "Mars") .mapMulti (s, c)-> {c.accept (s.toUpperCase ()); c.accept (s.toLowerCase ());}) .forEach (System.out::println); Output:TWIXtwixSNICKERSsnickersMARSmars

The same thing can be done in a way like flaMap:

Stream.of ("Twix", "Snickers", "Mars") .flatMap (s-> Stream.of (s.toUpperCase (), s.toLowerCase () .forEach (System.out::println)

So what's the difference between mapMulti and flatMap? According to javadocs:

This method is preferable to flatMap in the following situations:

When each stream element is replaced with a small number of (possibly zero) elements. Using this approach avoids the overhead of creating a new Stream instance for each set of result elements, as required by flatMap.

When it is easier to generate result elements using an imperative method than to return them as a stream.

Examining the code of multiMap, we can see that it is delegated to flatMap, but it SpinedBuffer uses a to save the element before creating the flow, thus avoiding the overhead of creating a new stream for each set of result elements.

Default Stream mapMulti (BiConsumer

Tags: Element method knowledge result cost industry different practical inter thing code content command imperative uppercase character string instance practicality actual Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Linux NVidia Microsoft Huawei