How to convert List into HashBasedTable using Java 8?

824 Views Asked by At

How can we convert a List into HashBasedTable in Java8?

Current Code is like:

import org.glassfish.jersey.internal.guava.HashBasedTable;
import org.glassfish.jersey.internal.guava.Table;

List<ApplicationUsage> appUsageFromDB = computerDao.findAllCompAppUsages(new HashSet<>(currentBatch));
Table<String, String, Integer> table = HashBasedTable.create();
for(ApplicationUsage au: appUsageFromDB) {
  table.put(au.getId(), au.getName(), au);
}

I need to store composite key in this and later fetch the same.

2

There are 2 best solutions below

0
Eugene On

If those internals are guava-21 at least, you could do via their own collector, but I do not see anything wrong with what you are doing with a simple loop.

Table<String, String, ApplicationUsage> result =
        appUsageFromDB.stream()
                      .collect(ImmutableTable.toImmutableTable(
                          ApplicationUsage::getId,
                          ApplicationUsage::getName,
                          Function.identity()
                      ));
2
Grzegorz Rożniecki On

First, you should never rely on internal packages, just add Guava to you project explicitly. You can use Tables#toTable collector, if you want to have mutable table as a result, otherwise immutable one as presented in @Eugene's answer is just fine:

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.collect.Tables;

// ...

    Table<String, String, ApplicationUsage> table2 = appUsageFromDB.stream()
            .collect(Tables.toTable(
                    ApplicationUsage::getId,
                    ApplicationUsage::getName,
                    au -> au,
                    HashBasedTable::create
            ));

Also, your code doesn't compile, because it expects Integer as table value, but you're adding ApplicationUsage in your loop. Change types and third argument in table collector accordingly if needed.