Converting a CustomObject List to a Guava Table Collection with Less Complexity

I have

class CustomObject {
Integer day;
List<InnerObject> innerObjects;
///getter setter

}

class InnerObject {
String id;
List<String> someVal;
//getter setter

}

I have

List<CustomObject>

I want too

Table<String, Integer, List<String>>

I want the table to represent id (from InnerObject)→ ( day (from Custom object),List of someVal (from InnerObject)

Just to clear, I changed the names a bit, but the structure is the same as expected.

Now, as I do,

final List<CustomObject> objects = ???
final Map<Integer, List<InnerObject>> dayVsInnerObjects = objects.stream()
.collect(toMap(CustomObject::getDay, CustomObject::getInnerObjects));


final Table<String, Integer, List<String>> table = HashBasedTable.create();

 dayVsInnerObjects.forEach((day, innerObjects) -> 
                            innerObjects.forEach(i -> {
                             table.put(i.getId(), day, i.getSomeVal());
            })
);

My questions:

  • Is there a better way to do this? may be the best guava / Collection API that can make it cleaner.
  • Now the table is populated, and it is changed. we have a way to make it immutable when you create it.
  • The complexity of time, if it can be reduced here.
+6
source share
2 answers

flatMap , Map.Entry<Integer, InnerObject> ( - ) Table Guava Tables.toTable :

Table<String, Integer, List<String>> table = objects.stream()
    .flatMap(custom -> custom.getInnerObjects().stream()
            .map(inner -> new SimpleEntry<>(custom.getDay(), inner)))
    .collect(Tables.toTable(
            entry -> entry.getValue().getId(),
            entry -> entry.getKey(),
            entry -> entry.getValue().getSomeVal(),
            HashBasedTable::create));

, Table , Guava Tables.unmodifiableTable:

Table<String, Integer, List<String>> unmodifiableTable = Tables.unmodifiableTable(table);

, unmodifiable Table :

Table<String, Integer, List<String>> unmodifiableTable = objects.stream()
    .flatMap(custom -> custom.getInnerObjects().stream()
            .map(inner -> new SimpleEntry<>(custom.getDay(), inner)))
    .collect(Collectors.collectingAndThen(
            Tables.toTable(
                    entry -> entry.getValue().getId(),
                    entry -> entry.getKey(),
                    entry -> entry.getValue().getSomeVal(),
                    HashBasedTable::create),
            Tables::unmodifiableTable);

. Guava 22.0, , , 21.0.

, , 1 2. 3, , , InnerObject CustomObject.

+6

, ( , Map):

.stream()
.collect((Collector.of(
       HashBasedTable::create, 
       (table, co) -> {
           for (InnerObject io : co.getInnerObjects()) {
                table.put(io.getId(), co.getDay(), io.getSomeVal());
           }
       }, 
       (left, right) -> {
            left.putAll(right);
            return left;
       }));

, - , version 21.

+1

All Articles