FAQ Database Discussion Community


How can I collect a Java 8 stream into a Guava ImmutableCollection?

java-8,guava,java-stream
I would like to do the following: List<Integer> list = IntStream.range(0, 7).collect(Collectors.toList()); but in a way that the resulting list is an implementation of Guava's ImmutableList. I know I could do List<Integer> list = IntStream.range(0, 7).collect(Collectors.toList()); List<Integer> immutableList = ImmutableList.copyOf(list); but I would like to collect to it directly. I've...

Guava Multimaps wildcard putAll

java,generics,guava
Struggling with a generics issue using Guava's Multimap class Foo{ ... private Multimap<Baz,? extends Bar> stuff; ... public void overWriteStuff(Multimap<Baz,? extends Bar> newstuff){ this.stuff.clear(); this.stuff.putAll(newStuff); } } This looks very straighforward to me, both stuff and the argument newstuff both have the same type yet I get a generics related...

Guava predicate to filter various conditions without anonymous class or extra classes

java,guava
With Java 6 and Guava 12.0 I am trying to filter a list of Strings based on if they have a specific prefix or not. Is there a way to do this without using anonymous classes or a separate class for each distinct prefix I want? This works but it's...

Using Guava 19.0, is there a way to map a file extension to a MediaType?

java,file,media,guava
I have a full file path and would like to determine the MediaType (Google's Guava 19.0) it corresponds to. I thought there would be a built in function in MediaType to accomplish this but I don't think so after experimenting and reading the MediaType API. I know I can accomplish...

Passing generic event to Guava EventBus?

java,swing,generics,reflection,guava
I've become very fond of Google Gauva's EventBus, so much that I want to include it in one of my Swing GridBagBuilder API's. The goal is to take a Swing component and do something with it in an arbitrary event, and subscribe this to an EventBus. The problem is I...

Why can this function return a null possibly?

java,nullpointerexception,guava
Imagine I had a guava helper function private Function<Config, Predicate<String>> makeFunctionToCompareTwoPathStrings() throws ConfigException { return new Function<Config, Predicate<String>>() { @Override public Predicate<String> apply(final Config config) { try { final Path input = computationThatMightThrowAnException(); return new Predicate<String>() { @Override public boolean apply(String actual) { return input.toAbsolutePath().toString().equalsIgnoreCase(actual); } }; } catch (ConfigException...

How long does an event live in the eventbus?

java,guava
I would like to @Subscribe a method in a Runnable that is created by a ScheduledFuture, so that I can signal it from another thread whether to run. Because a ScheduledFuture creates the object at some future time, there is no scope for the @Subscribe listener to pick up my...

Should I use the Guava-base-libaries at JCenter or are there other places to get modularized Guava-jars?

android,guava,jcenter
The Guava-libararies at JCenter/Maven Central come in different flavors either the entire lib of 2205KB or in modules such as guava-base of 100KB I'm just worried that the latter apparently is not updated in five years, and has a version 'RC3'. Yet I'd like to have some place to get...

Preconditions library to throw IllegalArgumentException for notNull check

java,nullpointerexception,guava,apache-commons,preconditions
Do you know some nice alternative to Apache Commons Validate or Guava Preconditions that would throw IllegalArgumentException instead of NullPointerException when checking if object is not null (except Spring Assert)? I'm aware that Javadocs say: Applications should throw instances of this class [NullPointerException] to indicate other illegal uses of the...

How is Guava Splitter.onPattern(..).split() different from String.split(..)?

java,regex,split,guava
I recently harnessed the power of a look-ahead regular expression to split a String: "abc8".split("(?=\\d)|\\W") If printed to the console this expression returns: [abc, 8] Very pleased with this result, I wanted to transfer this to Guava for further development, which looked like this: Splitter.onPattern("(?=\\d)|\\W").split("abc8") To my surprise the output...

EventBus and Swing JFrame Garbage Collection?

java,swing,garbage-collection,guava,event-bus
I am refactoring a Swing application to use Guava's EventBus pretty heavily. The Swing application basically runs a decision process, displays a large collection of results in a JFrame, and then gets disposed once the JFrame is closed. Now it also subscribes to an EventBus to handle user manipulation of...

Difference between new HashMap(int) and guava Maps.newHashMapWithExpectedSize(int)

java,collections,guava
In Java, you can create a new HashMap to hold a specific number of items like so: Map m = new HashMap(100); Guava provides a Maps.newHashMapWithExpectedSize(int) method, which I would expect to simply call HashMap(int). But it doesn't do this, instead it calculates its own capacity and uses that. Why...

How to index a multimap based on several criteria?

java,guava
I have a List of "SomeClass" which may consist of a lot of functionally equal objects, and I need to group these. The entries with identical getName(), getInputDate(), getOutputDate() and getValue() should be grouped together. I came across Multimap which seems to be what i need, but I can't figure...

Invokable.getReturnType(): cannot reproduce Guava's example from the official wiki

java,reflection,guava
In the official Guava's TypeToken wiki, there is the following example: Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {}.method(getMethod); invokable.getReturnType(); // String.class How getMethod is set? I tried the following examples: First try: List<String> list = new ArrayList<String>(); Class[] arg = { int.class }; Method getMethod = list.getClass().getMethod("get", arg); Invokable<List<String>, ?>...

Iterating over Guava Mutlimaps

java,collections,guava,multimap
Is there a way to get a Key-Value pair of each element in a MultiMap in each iteration, without first adding them to a list? I'd like to implement something like this: (I know this will not work) public class MutliMapTest { public static void main(String... args) { Multimap<String, String>...

Extracting data from a HashBasedTable (a Guava collection) using index values

java,collections,guava
I have a method that returns a HashBasedTable (from Google's Guava project : https://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Table) i'm looking to extract values out of that table, after its been created. import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; /** * * @author yschellekens */ public class StackOverflow { /** * * @return */ public static Table<Long, Long,...

In spring make sure Guava Event Bus listener beans are instantiated before events are dispatched

java,spring,events,guava,dependency-management
Say I have the following: Config Sets up the guava EventBus bean. @Configuration public class AppConfig { @Bean public EventBus eventBus() { return new EventBus(); // guava event bus } } Event listener Listens and handles to some/all of the events that are put on the event bus. May have...

Difference between Iterables.tryFind and FluentIterable.firstMatch in Guava

java,guava
Is there any difference between? MyObject myWantedObj = Iterables.tryFind(myListOfObjects, new Predicate<MyObject>() { public boolean apply(MyObject myObj) { return myObj.getSomeAttribute().equals(someFinalVariable); } }).orNull(); and MyObject myWantedObj = FluentIterable.from(myListOfObjects).firstMatch(new Predicate<MyObject>() { public boolean apply(MyObject myObj) { return myObj.getSomeAttribute().equals(someFinalVariable); } }).orNull(); Iterables.tryFind and FluentIterable.firstMatch Javadoc are equals to: Returns an...

how to convert java Future to guava ListenableFuture

java,concurrency,guava,futuretask
I need to find a way to convert from Future to ListenableFuture. Currently i'm using a service which returns Future but i need to hook up a listener to it. I can't change the service interface as it doesn't belong to me. Is there a simple way to do that...

Looking for java 1.6 workaround to apparent compiler issue

java,generics,guava,java-6
This compiles fine with Java 1.7 but not with 1.6. (This is using Guava 14.0.1). Cache<TokenCacheKey, CachedToken>tokenCache = CacheBuilder.<TokenCacheKey, CachedToken>from(PARAM.tokenCacheConfig).build(); Can anyone suggest an alternative that can be compiled in 1.6?...

Java Optional for method argument?

java,java-8,guava,optional
I was reading this post on using Optionals for method arguments and the consensus seems to be to never use them for that purpose. Guava Optional as method argument for optional parameters But are there exceptions to this rule at all on the API side (not application side)? I can't...

Reading Multimap with composite key including null field

java,collections,guava,multimap
I have a Multimap to store some data with composite key (data type, data id). Here is my code: public class Data { private final String type; private final Integer id; private final String information; public Data(String type, Integer id, String information) { this.type = type; this.id = id; this.information...

Murmur3 hash different result between Python and Java implementation

java,python,guava,murmurhash
I have two different program that wish to hash same string using Murmur3 in Python and Java respectively. Python version 2.7.9: mmh3.hash128('abc') Gives 79267961763742113019008347020647561319L. Java is Guava 18.0: HashCode hashCode = Hashing.murmur3_128().newHasher().putString("abc", StandardCharsets.UTF_8).hash(); Gives string "6778ad3f3f3f96b4522dca264174a23b", converting to BigInterger gives 137537073056680613988840834069010096699. How to get same result from both? Thanks...

Getting the first object that satisfies condition

java,guava
I have a problem with downloading the first object in the list that meets the condition. My code always returns the first object that is on the list, regardless of condition. Returns the person with id = 1. main(){ public static void main(String args[]) { List<Person> persons = Lists.newArrayList(); persons.add(new...

Guava AbstractScheduledService on server environment

java,thread-safety,guava,scheduler
What is the preferred way of shutting down an AbstractScheduledService running in server environment (e.g. Tomcat) when the application server is shutting down? Do I have to explicitly register a server listener for this, or is there a way to specify the service threads as daemons?

Google Guava Hashing

hash,guava
I have some problem with guava funnel , I read this article https://code.google.com/p/guava-libraries/wiki/HashingExplained and others , but I don't know how I can use funnel when my class contains not only primitive types. Funnel<Person> personFunnel = new Funnel<Person>() { @Override public void funnel(Person person, PrimitiveSink into) { into .putInt(person.id) .putString(person.firstName,...

Does Jackson support java 8 stream()?

json,jackson,java-8,guava,java-stream
I would like to use Jackson's Tree Model with Java 8 stream API, like so: JsonNode jn = new ObjectMapper().readValue(src, JsonNode.class); return jn.stream().anyMatch(myPredicate); However, JsonNode does not seem to implement stream() and I could not find any standard helpers to do so. JsonNode implements Iterable, so I can achieve the...

NoSuchMethodError: com.google.common.base.Stopwatch.createStarted()Lcom/google/common/base/Stopwatch

java,guava,restlet,apispark
My app is throwing NoSuchMethodError: com.google.common.base.Stopwatch.createStarted()Lcom/google/common/base/Stopwatch error. Not sure why, because 16.0.1 do contain that class, I've checked. From what I have researched, it looks like this is a bug? I also have this code for refernence, though I think this is not the issue: FirewallRule rule = new PeriodicFirewallCounterRule(60,...

Guava Transform Map> to List

java,guava
I have to transform/convert source object into target object. Please see the sample code below using Guava. Below is a test class where i have a Source object as Map<String, List<Double>> which i need to transform it to Target. public class TestMapper { public static void main(String[] args) { String...

Is there a with() method inside ImmutableMap?

java,guava,immutable-collections
I am watching the video (https://www.youtube.com/watch?v=ZeO_J2OcHYM) and find that we can initialize the ImmutableMap using the with() method. See below: public static final ImmutableMap<String, Integer> ENGLISH_TO_INT = ImmutableMap .with("four", 4) .with("eight", 8) .with("fifteen", 15) .with("sixteen", 16) .with("twenty-three", 23) .with("forty-two", 42) .build(); However, when I check the API of ImmutableMap, I...

How can I use Joiner, to join only specific properties?

java,guava,joiner
Let's say I have this class: public class MyClass { private String propertyOne; private String propertyTwo; // getters setters... } Now, in my test method, I am trying something like: List<MyClass> myList = myListDao.findAll(); String aStringFullOfPropertyOnesOfAllMyObjects = Joiner.on(", ").join(myList.iterator()); The String, I want to get back is something like: "propOneOfObjectOne,...

Why Does Checkers in Google Precondition Library take object in stead of a String

java,gwt,guava,preconditions
Why does check* methods in Google Precondition library take an Object instead of a String? I can see that the object is called String.valueOf() on. I think this design was due to not making any assumption on behalf of the client. But I cannot think about a reasonable case where...

Iterating over a map and putting its values in java

java,guava
I have created the data structure that is google based guava table and it is shown below final Table<String, String, List<String>> values = HashBasedTable.create(); values.put("ton bon", "currency", Lists.newArrayList("ccdd", "rode1", "cwey", "Certy")); values.put("ton bon", "racy", Lists.newArrayList("wqadd", "werde", "ihtr", "ytre")); Below is the way in which i am iterating over this collection...

Guava EventBus throwing handlerExcetion when different instances of the same class are registered on the bus

java,swing,event-handling,guava
I am having difficulty registering multiple instances of the same class onto one Google guava event bus. If a single instance of a class is registered, it runs fine, if I try to register more then one instance, it throws a handlerException. Full error: Feb 24, 2015 10:37:25 PM com.google.common.eventbus.EventBus$LoggingSubscriberExceptionHandler...

How do I concatenate two lists to create a 3rd?

java,guava
I've been googling for this, and I found this answer. There is an Iterables.concat in guava. But this returns an Iterable and the next thing I want to do is sort the result. Collections.sort takes in a List, not an Iterable so I'd have to convert the Iterable into a...

Create Multimap from Map> with key as V[0] and value as K using Java 8

java-8,guava
I have a Map<String,List<String>>(say inputMap) and I want to convert this to another Map<String,List<String>> where each (k,v) in the new map is (v.get(0),k) of inputMap. Ex. X -> B,C,D Y -> B,D,E Z -> B,G,H P -> A,B,D Q -> A,D,F R -> A,C,B to B->X,Y,Z A->P,Q,R I initially thought...

What exception should be thrown when Guava CacheLoader is unable to load the data?

java,guava
I am implementing simple guava CacheLoader as it is stated here CacheLoader<Key, Graph> loader = new CacheLoader<Key, Graph>() { public Graph load(Key key) throws AnyException { return createExpensiveGraph(key); } }; LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder().build(loader); Does this mean that I should create my own exception class and throw it if...

How to wrap a method that returns an optional with fromNullable?

java-8,guava,optional
I have a method that I don't own that is returning null but return type is Optional<Boolean>. When I call x.IsPresent() it throws (scenario #2). I tried wrapping the method in a fromNullable but I get a type mismatch (screen shot below). How can I fix so IsPresent() doesn't throw?...

How can I transform a List into List?

java,list,guava
If A is defined like this: class A { List<B> bList; } If a List of A's is given (List aList), how can I transform it into a List containing all the B's that are stored in each element from aList? I would want to use guava to do this....

How do I store a Map in a Guava Cache

java,caching,dictionary,guava
I had a Map<Range<Double>, String> that checks where a particular Double value (score) is mapped to a String (level). The end users want to be able to dynamically change this mapping, in the long term we would like for there to be a web based GUI where they control this...

How do I ask for a parameter to be a mutable Map?

java,collections,guava
I have a function that accepts a Map of parameters, but adds to them before using them: public String doRequest(String endpoint, Map<String, String> parameters) { parameters.put("limit", "50"); ... } It's convenient to create this map using Guava's ImmutableMap.of(): doRequest("/comments", ImmutableMap.of("filter", "true")); However, this throws a java.lang.UnsupportedOperationException at runtime. Two questions:...

Java - multiline string to array

java,arrays,guava
i have multiline string : 40 40 40 100 100 100 200 200 200 100 50 200 100 150 150 150 50 60 70 80 90 and I need it as 2D array. I was trying to do it by split, guava Splitter and couple of more techniques but it...

FileBackedOutputStream on Appengine

java,google-app-engine,out-of-memory,guava,securityexception
My application on Appengine create a csv file with more 65535 rows But, I have an error of type OutOfMemoryError when writing : java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOf(Arrays.java:2271) at java.io.ByteArrayOutputStream.grow(ByteArrayOutputStream.java:118) at java.io.ByteArrayOutputStream.ensureCapacity(ByteArrayOutputStream.java:93) at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:153) White this code : public static byte[] joinLines(Collection<String> lines) { final...

Is there a way to bind a couple of instances to many different keys in Guice?

java,collections,guava,guice
We need to create some mapping between many types of some object, described with enum values: public enum ObjectType { Type1,Type2,Type3,Type4,Type5...TypeN } ... and several instances of strategies to use for these types or, for example, boolean values which relate to the mentioned ObjectTypes A MapBinder from Guice can be...

How to port from java.util.Optional method call chaining to Guava Optional?

java,java-8,guava,optional
I have the following that uses java.util.optional // this works fine for java.util.Optional Optional <Context> xx = Optional.ofNullable(x); Optional<DateRange> dates = xx.map(Context::getEntity).map(Entitiy::getDates); However, I need to convert that to use guava's optional. I tried something like guava Optional transform but I'm unsure how to chain something like this with guava...

Does Guava support Contract Classes, or otherwise allow interface documentation?

java,guava,contracts
I was looking at Guava's Preconditions. It's great if you are using them in an implementation method, but is it possible to state interface contracts using them? For example, in C# Contracts you can do this - using System.Diagnostics.Contracts; [ContractClass(typeof(FooContract))] interface IFoo { void Bar(int i); } [ContractClassFor(typeof(IFoo))] abstract class...

Is ImmutableMap a sub-optimal choice for large volume of keys/objects/

java,collections,hashmap,guava
I was doing some tests with a colleague, and we were pulling data in from a database (about 350,000 records), converting each record into an object and a key object, and then populating them into an ImmutableMap.Builder. When we called the build() method it took forever, probably due to all...

Shortest way to extract Map from List in Java

java,collections,java-7,guava
I have a List List<FeatureHolder> featureHolderList; consisting of FeatureHolder objects public class FeatureHolder { private String flag; private String value; } Now I need to extract Map from the featureSetList. The solution is, of course, trivial: Map<String, String> map = new HashMap<>(); for(FeatureHolder fh: featureHolderList){ map.put(fh.getFlag(), fh.getValue()); } The question...

Equivalent in java 8 from guava Enums.getIfPresent() that will return java.util.Optional?

java-8,guava,optional
I have the following code from an old group that is using guava Optional and Enums (getIfPresent). // getNameAsString returns the string literal but I want to safely convert // to an enum and return an java.util.Optional <MessageName>. // MessageName is an enum Optional<MessageName> msgName = Enums.getIfPresent(MessageName.class, obj.getMessage().getNameAsString()); How can...

How can i do to get all class of a given package with guava

java,reflection,package,guava
I am working on a maven projet and i added to my pom.xml file the guava dependency and the dependency of an other project. I want to get all class of a given package of that project whitch added to my pom as a dependency. So i tried with this...

Ensure List of elements ordered by field in element

collections,java-8,guava,method-reference
Using Guava it is possible to ensure ascending ordering this way: import com.google.common.collect.Ordering; import io.predictor.dao.ohlcv.OhlcvHm; import static java.util.stream.Collectors.toList; assertThat("Ordered by age", Ordering.natural().isOrdered( employees.stream().map(Employee::getAge).collect(toList()))); It is strange for me that Guava (for all its close relation to Java lambdas) does not provide easy solution for such cases. Of course I can...

Why does FluentIterable.first() throw NPE when the first element is null

guava
Here is the method description for FluentIterable.first(). It throws a NPE but not return Optional.absent() when the first element is null. I think it makes FluentIterable influent, and Optional as the return value gives me an impression that it's totally safe. I wonder why? Thanks....

NullPointerException caused by Reading from File used for indexing using Google Guava [duplicate]

java,indexing,guava,bufferedreader,multimap
This question already has an answer here: What is a Null Pointer Exception, and how do I fix it? 12 answers I am working with Google Guava to use a Multimap like this for example {S1.E11=[S2.E236], S1.E108=[S2.E371]} . But I have a problem. I want to read from file...

Java 8 collector for Guava immutable collections?

java,guava,java-stream
I really like Java 8 streams and Guava's immutable collections, but I can't figure out how to use the two together. For example, how do I implement a Java 8 Collector that gathers stream results into an ImmutableMultimap? Bonus points: I'd like to be able to provide key/value mappers, similar...

Neo4j and Java: fast and random sample of Iterable

java,neo4j,guava
I've coded a traversal in Java which returns an Iterable. The worst case is an Iterable size of 850784 relationships. Objective: I want to sample (without replacement) only 20 relationships and I want to do it fast. Solution 1 : performing a toList() or casting it in some sort of...

Guava Hasher some times give diff result for same object

java,guava
I need create a hash code from Map with Key(Custom Object) and Value As Set of custom object, i Use Guava 18.0 @Getter public final class StockKey { @ValidIsin private final String isin; @ValidExchangeId private final Integer exchangeId; @ValidCurrency private final String currency } @EqualsAndHashCode public final class ClientAssetPosition {...

Is there any way to copy a directory to another path using guava library?

java,directory,copy,guava
I know there is a method -Files.copy()- using guava library to copy a file, but what's the way to copy a directory in other path? P.S: this question maybe similar to this question but I'm wondering if there is any other way except copying files one by one.

Guava: MemoizingSupplier thread safety

java,concurrency,guava
Guava Suppliers-class contains MemoizingSupplier: static class MemoizingSupplier<T> implements Supplier<T>, Serializable { final Supplier<T> delegate; transient volatile boolean initialized; // "value" does not need to be volatile; visibility piggy-backs // on volatile read of "initialized". transient T value; MemoizingSupplier(Supplier<T> delegate) { this.delegate = delegate; } @Override public T get() { //...

Best way to return null from a method?

java,guava,apache-commons
I need to get the hostname of the machine where the code is running. I have a method like this: private static final String getHostName() { try { return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase(); } catch (UnknownHostException ex) { logger.logError("error = ", ex); } // this looks pretty odd to me, are there any...

Different results from Murmur3 from Scala and Guava

scala,guava,consistent-hashing,murmurhash
I am trying to generate hashes using the Murmur3 algorithm. The hashes are consistent but they are different values being returned by Scala and Guava. class package$Test extends FunSuite { test("Generate hashes") { println(s"Seed = ${MurmurHash3.stringSeed}") val vs = Set("abc", "test", "bucket", 111.toString) vs.foreach { x => println(s"[SCALA] Hash for...

How to build a ConcurrentLinkedHashmap using Guava?

guava
Several links show that https://code.google.com/p/concurrentlinkedhashmap/ has been ported to Guava, but I can not find the corresponding API in Guava. Can anybody show me an example to build a ConcurrentLinkedHashmap using Guava ? Thanks!...

difference between a getter method and a method which returns the state of an instance variable?

java,guava
I am reading through the Guava library, and I keep running into methods that look something like this: @Override public int size() { return size; } What is the difference (strategically, conventionally, etc) between the above and the following? @Override public int getSize() { return size; } Or is there...

How to throw away the original collection once the Immutable version is created using Google Guava?

java,guava,immutability
I have a map as below and once I get the immutable version of the original map, I don't need the original one anymore. Is there a way to have the GC recycle it? Map<String, String> map = new TreeMap<>(); map.put("1", "one"); map.put("2", "two"); map.put("3", "three"); ImmutableMap<String, String> IMMUTABLE_MAP =...

What is the impact of libraries that maintain their own threads pool?

concurrency,threadpool,guava,hystrix
I'm using Google Guava and Netflix Hystrix libraries in our project. Each library comes with it is own pool of threads that you can configure. Thats made think of the impact of that. I mean each library is maintaining its own pool of threads and of course, each hardware has...

Swapping relation of keys and values in a Google Guava Multimap

java,guava,relation,multimap
I have a Multimap<String, Integer> map = ... where I can do map.get("somekey") to retrieve all the matching Integers. Now I would like to find the keys that have a given Integer, i.e. something like a Collection<String> keys = map.getByValue(Integer.of(4)) which returns all keys in the Multimap where the given...

How can I use a guava class (HashMultiset) from Scala?

java,scala,guava
Here are some of my failed attempts: import com.google.common.collect.HashMultiset // 1. This does not work! // val foo1:HashMultiset[Int] = HashMultiset[Int].create() // 2. Neither does this! // val foo2:HashMultiset[Int] = new HashMultiset[Int]() // foo1.add(1) In the first case it complains that HashMultiset is not a value. In the second case it...

Mocking db queries with querydsl - issue with Optional

java,junit,mocking,guava,querydsl
I've some difficulties to write tests on DB queries for my application, which uses querydsl on top of a mongo. I've found several examples of people who just unit-test the query object itself, but I'd like to go a step further and test how the query performs (like an integration...

Guava Sets.intersection bad performance

java,performance,collections,set,guava
I've encountered a strange problem in production today. Though I love Guava, I ran into a use case where Guava's Sets.intersection() was performing pretty badly. I've written a sample code: Set<Long> cache = new HashSet<>(); for (long i = 0; i < 1000000; i++) { cache.add(i); } Set<Long> keys =...

Guava group by and order by members

guava
I want to group and order the elements by certain members in guava instead of sql. sql = "SELECT * FROM players GROUP BY club, country ORDER BY goals DESC"; When i try grouping by Multiset, it takes the entier class as a parameter and gives me back the list....

Is it possible to have a single Gson-based method to deserialize maps with values from different classes?

java,json,serialization,gson,guava
I have two methods that are virtually identical, both reading a map serialized as JSON. These are maps with multiple values per key, so I am converting the maps to guava Multimap. And I am using Gson for serializing and deserializing these maps. The relevant parts of the code follows:...

Joining a collection based on members of the type

java,functional-programming,guava,method-chaining
I have a class A and its members b and c. Now I construct the List<A> with this: add(new A().setb("abcd").setc("123456")); add(new A().setb("efgh").setc("789101")); add(new A().setb("ijkl").setc("112345")); I want to transform this List to string which looks like this abcd,123456 efgh,789101 ijkl,112345 Now the very obvious way would be to have a StringBuilder...