¿La forma más sencilla de iterar a través de un Multiset en el orden de frecuencia de elementos?
Considere este ejemplo que imprime algunas estadísticas de tipo de dispositivo. ("DeviceType" es una enumeración con valores dozenish.)
Multiset<DeviceType> histogram = getDeviceStats();
for (DeviceType type : histogram.elementSet()) {
System.out.println(type + ": " + histogram.count(type));
}
¿Cuál es la forma más simple y elegante de imprimir los distintos elementos en el orden de su frecuencia (el tipo más común primero)?
Con una mirada rápida a la Multiset
interfaz, no hay un método listo para esto, y ninguna de las implementaciones de Guava Multiset
(HashMultiset
, TreeMultiset
, etc) parecen mantener automáticamente los elementos ordenados por frecuencia bien.
4 answers
Acabo de añadir esta característica a Guava, ver aquí para el Javadoc.
Editar : ejemplo de uso de Multisets.copyHighestCountFirst()
según la pregunta original:
Multiset<DeviceType> histogram = getDeviceStats();
for (DeviceType type : Multisets.copyHighestCountFirst(histogram).elementSet()) {
System.out.println(type + ": " + histogram.count(type));
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-23 15:21:05
Aquí hay un método que devuelve un List
de entradas, ordenadas por frecuencia ( UPDATE : usó una bandera para alternar el orden ascendente / descendente y usó el juguete favorito de Guayaba: el Enum Singleton Pattern
, como se encuentra en Effective Java , Item 3):
private enum EntryComp implements Comparator<Multiset.Entry<?>>{
DESCENDING{
@Override
public int compare(final Entry<?> a, final Entry<?> b){
return Ints.compare(b.getCount(), a.getCount());
}
},
ASCENDING{
@Override
public int compare(final Entry<?> a, final Entry<?> b){
return Ints.compare(a.getCount(), b.getCount());
}
},
}
public static <E> List<Entry<E>> getEntriesSortedByFrequency(
final Multiset<E> ms, final boolean ascending){
final List<Entry<E>> entryList = Lists.newArrayList(ms.entrySet());
Collections.sort(entryList, ascending
? EntryComp.ASCENDING
: EntryComp.DESCENDING);
return entryList;
}
Código de prueba:
final Multiset<String> ms =
HashMultiset.create(Arrays.asList(
"One",
"Two", "Two",
"Three", "Three", "Three",
"Four", "Four", "Four", "Four"
));
System.out.println("ascending:");
for(final Entry<String> entry : getEntriesSortedByFrequency(ms, true)){
System.out.println(MessageFormat.format("{0} ({1})",
entry.getElement(), entry.getCount()));
}
System.out.println("descending:");
for(final Entry<String> entry : getEntriesSortedByFrequency(ms, false)){
System.out.println(MessageFormat.format("{0} ({1})",
entry.getElement(), entry.getCount()));
}
Salida:
Ascendente:
Uno (1)
Dos (2)
Tres (3)
Cuatro (4)
descendente:
Cuatro (4)
Tres (3)
Dos (2)
Uno (1)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-03 15:17:16
Una Implementación usando ForwardingMultiSet :
(EntryComp de seanizer del respuesta)
enum EntryComp implements Comparator<Multiset.Entry<?>> {
DESCENDING {
@Override
public int compare(final Entry<?> a, final Entry<?> b) {
return Ints.compare(b.getCount(), a.getCount());
}
},
ASCENDING {
@Override
public int compare(final Entry<?> a, final Entry<?> b) {
return Ints.compare(a.getCount(), b.getCount());
}
},
}
public class FreqSortMultiSet<E> extends ForwardingMultiset<E> {
Multiset<E> delegate;
EntryComp comp;
public FreqSortMultiSet(Multiset<E> delegate, boolean ascending) {
this.delegate = delegate;
if (ascending)
this.comp = EntryComp.ASCENDING;
else
this.comp = EntryComp.DESCENDING;
}
@Override
protected Multiset<E> delegate() {
return delegate;
}
@Override
public Set<Entry<E>> entrySet() {
TreeSet<Entry<E>> sortedEntrySet = new TreeSet<Entry<E>>(comp);
sortedEntrySet.addAll(delegate.entrySet());
return sortedEntrySet;
}
@Override
public Set<E> elementSet() {
Set<E> sortedEntrySet = new LinkedHashSet<E>();
for (Entry<E> en : entrySet())
sortedEntrySet.add(en.getElement());
return sortedEntrySet;
}
public static <E> FreqSortMultiSet<E> create(boolean ascending) {
return new FreqSortMultiSet<E>(HashMultiset.<E> create(), ascending);
}
/*
* For Testing
* public static void main(String[] args) {
Multiset<String> s = FreqSortMultiSet.create(false);
s.add("Hello");
s.add("Hello");
s.setCount("World", 3);
s.setCount("Bye", 5);
System.out.println(s.entrySet());
}*/
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-23 15:20:00
Dado que todavía no está implementado, supongo que puede crear un Map
con key=type y value=count. A continuación, ordenar ese mapa-ver aquí
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:17:25