Java Reference
In-Depth Information
Listing 5-2. Assigning a Value to Each Element of a Stream of POJOs vs. a Stream of FuJIs
import java.util.stream.*;
public class Listing2 {
public static void main(String[] args) {
// Set Constant Value on a Stream of POJOs
Stream<PojoWordUsage> pojos = Stream.of(/* INSERT POJOS HERE */);
pojos.map(pojo -> {
pojo.setTextName("New Text Name");
return pojo;
}
);
// Set Constant Value on a Stream of FuJIs
Stream<WordUsage> fujis = Stream.of(/* INSERT FUJIS HERE */);
fujis.map(fuji -> fuji.withTextName("New Text Name"));
}
}
If you have a template object and want to work with data assigned by the stream, then the FuJI is
significantly more efficient: that code is given in Listing 5-3. In that case, we have a single POJO whose value
we keep assigning, which will probably work fine as long as we guarantee that the stream is single threaded
and executing in the same thread as the allocation of the object. The FuJI, on the other hand, will produce
new instances of the object on every pass of the stream, which will work no matter how concurrent the
stream may be. The FuJI code also happens to be shorter and more readable, too.
Listing 5-3. Mapping a Stream of Input Data to a Template POJO vs. a Template FuJI
import java.util.stream.*;
public class Listing3 {
public static void main(String[] args) {
WordUsage template = new WordUsage("some text", 0, "word", 1);
PojoWordUsage pojoTemplate = new PojoWordUsage("some text", 0, "word", 1);
Stream<Integer> lineOffsets = Stream.of(/* INSERT LINE OFFSETS HERE*/);
// Using POJO Template (not threadsafe)
Stream<PojoWordUsage> assignedPojos = lineOffsets.map(offset -> {
pojoTemplate.setLineOffset(offset);
return pojoTemplate;
}
);
// Using FuJI Template (threadsafe)
Stream<WordUsage> assignedFujis =
lineOffsets.map(template::withLineOffset);
}
}
 
Search WWH ::




Custom Search