Converting from one to another using Guava

I have a situation where I want to extract multiple values โ€‹โ€‹from several source objects into a collection. I tried to achieve this using the Guava transform, but I ran into the problem that I was returning a collection of collections that I had to "smooth out" manually. Is there a good way to return results directly to a flat collection?

private static final Function<Target, Collection<Integer>> EXTRACT_FUNCTION = new Function<SourceObject, Collection<Integer>>() { @Override public Collection<Integer> apply(SourceObject o) { // extract and return a collection of integers from o return Lists.newArrayList(..); } }; Collection<SourceObject> sourceObjects = ... Collection<Collection<Integer>>> nestedResults = transform(sourceObjects, EXTRACT_FUNCTION); // Now I have to manually flatten the results by looping and doing addAll over the nestedResults.. // Can this be avoided? Collection<Integer> results = flattenNestedResults(nestedResults); 
+4
source share
2 answers

You can use Guava Iterables.concat(Iterable<E>... coll) to group multiple duplicate results

+8
source

What you are asking is the reduce / fold method. Guava does not currently support it, although there is an open problem: http://code.google.com/p/guava-libraries/issues/detail?id=218

Maybe this is the best idea that you are not using Function , but you are repeating it and adding it to the same collection. Guava is a great infrastructure, but it cannot do everything.

+1
source

Source: https://habr.com/ru/post/1385302/


All Articles