find key with highest value in HashMap<String,Double> using lambdaj (java)

StackOverflow https://stackoverflow.com/questions/7234598

  •  15-01-2021
  •  | 
  •  

سؤال

I try to find the find key having the hightest value in a HashMap < String,Double > using lambdaj. I guess selectMax() will help, but I don't know how to use it in this case.

هل كانت مفيدة؟

المحلول

I've downloaded lambdaj and gave it a try. Here you go

import static ch.lambdaj.Lambda.having;
import static ch.lambdaj.Lambda.max;
import static ch.lambdaj.Lambda.on;
import static ch.lambdaj.Lambda.select;
import static org.hamcrest.Matchers.equalTo;

import java.util.HashMap;
import java.util.Map;


public class LambdaJtester {

    public static void main(String[] args) {
        final HashMap < String,Double >  mapp = new HashMap<String, Double>();
        mapp.put("s3.5", 3.5);
        mapp.put("s1.5", 1.5);
        mapp.put("s0.5", 0.5);
        mapp.put("s0.6", 0.6);
        mapp.put("2s3.5", 3.5);
        mapp.put("s2.6", 2.6);
        System.out.println(
                select(mapp.entrySet(), having(on(Map.Entry.class).getValue(), 
                        equalTo(max(mapp, on(Double.class)))))
        );
    }
}

prints out [2s3.5=3.5, s3.5=3.5]

نصائح أخرى

have you tried this?

java.util.HashMap <String,Double> map;
java.util.Map.Entry<String,Double> entry;
double maxx = selectMax(map, on(entry.getClass()).getValue())
/**
 * @return the key of the highest value of this map. Note: if this map has
 *         multiple values that are the highest, it returns one of its
 *         corresponding keys.
 */
public static <K, V extends Comparable<V>> K keyOfHighestValue(Map<K, V> map) {
    K bestKey = null;
    V bestValue = null;
    for (Entry<K, V> entry : map.entrySet()) {
        if (bestValue == null || entry.getValue().compareTo(bestValue) > 0) {
            bestKey = entry.getKey();
            bestValue = entry.getValue();
        }
    }
    return bestKey;
}

And one test:

import static org.junit.Assert.*;

import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class MapUtilsTest {

    @Test
    public void testKeyOfHighestValue() {

        Map<String, Double> mapp = new HashMap<String, Double>();
        mapp.put("s3.5", 3.5);
        mapp.put("s1.5", 1.5);
        mapp.put("s0.5", 0.5);
        mapp.put("s0.6", 0.6);
        mapp.put("2s3.5", 123.5); 
        mapp.put("s2.6", 2.6);

        assertEquals("2s3.5", MapUtils.keyOfHighestValue(mapp));
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top