sidss sidss - 3 months ago 51
Java Question

Java 8 collector for Guava Immutable Table

Use case:

Process list of string via method which returns

ImmutableTable
of type
{R,C,V}
. For instance
ImmutableTable of {Integer,String,Boolean} process(String item){...}


Collect the result i.e, merge all results and return
ImmutableTable
. Is there a way to achieve it?

Tried to write collector but couldn't get it right. Any help will great.

EDIT: Instead of writing collector I did it like this but I wonder if there is a better way to achieve this.

Builder<Integer, String, Boolean> tableBuilder =
ImmutableTable.builder();
listToProcess.parallelStream().forEach(itemString -> {
try (InputStreamReader reader = getSomeStream(itemString)) {
tableBuilder.putAll(someBuilder.buildTable(reader));
} catch (final Exception e) {/*...*/}
});


Edit :

How about using parallel stream ? Is there any concurrency issues here?

ImmutableTable<Integer, String, Boolean> buildData() {

// list of 4 AwsS3KeyName
listToProcess.parallelStream()

//Create new instance via Guice dependency injection
.map(s3KeyName -> ProcessorInstanceProvider.get()
.fetchAndBuild(s3KeyName))
.forEach(tableBuilder::putAll); return tableBuilder.build(); }

Answer

Something like this should work:

List<String> list; // given
ImmutableTable.Builder builder = new ImmutableTable.Builder();
list.stream()
    .map(processor::process) // converts String to ImmutableTable
    .forEach(builder::putAll);
ImmutableTable result = builder.build();