If I have a Guava Multimap, how would I sort the entries based on the number of values for the given key?
For instance:
Multimap<String, String> multiMap = ArrayListMultimap.create();
multiMap.put("foo", "1");
multiMap.put("bar", "2");
multiMap.put("bar", "3");
multiMap.put("bar", "99");
Given this, when iterating over multiMap, how would I get the "bar" entries to come first (since "bar" has 3 values vs. only 1 for "foo")?
Extract the entries in a list, then sort the list :
List<Map.Entry<String, String>> entries = new ArrayList<Map.Entry<String, String>>(map.entries());
Collections.sort(entries, new Comparator<Map.Entry<String, String>>() {
@Override
public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
return Ints.compare(map.get(e2.getKey()).size(), map.get(e1.getKey()).size());
}
});
Then iterate over the entries.
Edit :
If what you want is in fact iterate over the entries of the inner map ( Entry<String, Collection<String>>
), then do the following :
List<Map.Entry<String, Collection<String>>> entries =
new ArrayList<Map.Entry<String, Collection<String>>>(map.asMap().entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Collection<String>>>() {
@Override
public int compare(Map.Entry<String, Collection<String>> e1,
Map.Entry<String, Collection<String>> e2) {
return Ints.compare(e2.getValue().size(), e1.getValue().size());
}
});
// and now iterate
for (Map.Entry<String, Collection<String>> entry : entries) {
System.out.println("Key = " + entry.getKey());
for (String value : entry.getValue()) {
System.out.println(" Value = " + value);
}
}
I'd use the Multimap's keys Multiset entries, sort them by descending frequency (which will be easier once the functionality described in issue 356 is added to Guava), and build a new Multimap by iterating the sorted keys, getting values from the original Multimap:
/**
* @return a {@link Multimap} whose entries are sorted by descending frequency
*/
public Multimap<String, String> sortedByDescendingFrequency(Multimap<String, String> multimap) {
// ImmutableMultimap.Builder preserves key/value order
ImmutableMultimap.Builder<String, String> result = ImmutableMultimap.builder();
for (Multiset.Entry<String> entry : DESCENDING_COUNT_ORDERING.sortedCopy(multimap.keys().entrySet())) {
result.putAll(entry.getElement(), multimap.get(entry.getElement()));
}
return result.build();
}
/**
* An {@link Ordering} that orders {@link Multiset.Entry Multiset entries} by ascending count.
*/
private static final Ordering<Multiset.Entry<?>> ASCENDING_COUNT_ORDERING = new Ordering<Multiset.Entry<?>>() {
@Override
public int compare(Multiset.Entry<?> left, Multiset.Entry<?> right) {
return Ints.compare(left.getCount(), right.getCount());
}
};
/**
* An {@link Ordering} that orders {@link Multiset.Entry Multiset entries} by descending count.
*/
private static final Ordering<Multiset.Entry<?>> DESCENDING_COUNT_ORDERING = ASCENDING_COUNT_ORDERING.reverse();
EDIT: THIS DOESN'T WORK IF SOME ENTRIES HAVE THE SAME FREQUENCY (see my comment)
Another approach, using an Ordering based on the Multimaps' keys Multiset, and ImmutableMultimap.Builder.orderKeysBy() :
/**
* @return a {@link Multimap} whose entries are sorted by descending frequency
*/
public Multimap<String, String> sortedByDescendingFrequency(Multimap<String, String> multimap) {
return ImmutableMultimap.<String, String>builder()
.orderKeysBy(descendingCountOrdering(multimap.keys()))
.putAll(multimap)
.build();
}
private static Ordering<String> descendingCountOrdering(final Multiset<String> multiset) {
return new Ordering<String>() {
@Override
public int compare(String left, String right) {
return Ints.compare(multiset.count(left), multiset.count(right));
}
};
}
Second approach is shorter, but I don't like the fact that the Ordering has state (it depends on the Multimap's key Multiset to compare keys).
Using Java8 streams:
ListMultimap<String, String> multiMap = ArrayListMultimap.create();
multiMap.put("foo", "f1");
multiMap.put("baz", "z1");
multiMap.put("baz", "z2");
multiMap.put("bar", "b1");
multiMap.put("bar", "b2");
multiMap.put("bar", "b3");
Multimaps.asMap(multiMap).entrySet().stream()
.sorted(Comparator.comparing(e -> -e.getValue().size()))
.forEach(e -> System.out.println(e.getKey() + " -> "
+ Arrays.toString(e.getValue().toArray())));
Output:
bar -> [b1, b2, b3]
baz -> [z1, z2]
foo -> [f1]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.