Java-get most common element in a list

In statistics, this is called the “mode”. A vanilla Java 8 solution looks like this: Stream.of(1, 3, 4, 3, 4, 3, 2, 3, 3, 3, 3, 3) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())) .entrySet() .stream() .max(Map.Entry.comparingByValue()) .ifPresent(System.out::println); Which yields: 3=8 jOOλ is a library that supports mode() on streams. The following program: System.out.println( Seq.of(1, 3, 4, 3, 4, 3, … Read more

Get minvalue of a Map(Key,Double)

You can use the standard Collections#min() for this. Map<String, Double> map = new HashMap<String, Double>(); map.put(“1.1”, 1.1); map.put(“0.1”, 0.1); map.put(“2.1”, 2.1); Double min = Collections.min(map.values()); System.out.println(min); // 0.1 Update: since you need the key as well, well, I don’t see ways in Collections or Google Collections2 API since a Map is not a Collection. The … Read more

How to create a Multimap from a Map?

Assuming you have Map<String, Collection<String>> map = …; Multimap<String, String> multimap = ArrayListMultimap.create(); Then I believe this is the best you can do for (String key : map.keySet()) { multimap.putAll(key, map.get(key)); } or the more optimal, but harder to read for (Entry<String, Collection<String>> entry : map.entrySet()) { multimap.putAll(entry.getKey(), entry.getValue()); }

java.lang.NoSuchMethodError: com.google.common.io.ByteStreams.exhaust(Ljava/io/InputStream;)J

With some IDE there’s a plugin to debug this kind of case. Anyway google-api-client 1.22.0, as you can see, depends on guava-jdk5 17. That version is in conflict with google-out-library.oath2-http that need version of guava > 20 Try to modify your pom.xml like this <dependency> <groupId>com.google.api-client</groupId> <artifactId>google-api-client</artifactId> <version>1.22.0</version> <exclusions> <exclusion> <groupId>com.google.guava</groupId> <artifactId>guava-jdk5</artifactId> </exclusion> </exclusions> </dependency> … Read more

Filtering a list of JavaBeans with Google Guava

Do it the old-fashioned way, without Guava. (Speaking as a Guava developer.) List<Person> filtered = Lists.newArrayList(); for(Person p : allPersons) { if(acceptedNames.contains(p.getName())) { filtered.add(p); } } You can do this with Guava, but Java isn’t Python, and trying to make it into Python is just going to perpetuate awkward and unreadable code. Guava’s functional utilities … Read more