Reputation: 48
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.
Upvotes: 2
Views: 6887
Reputation: 16501
/**
* @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));
}
}
Upvotes: 0
Reputation: 16037
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]
Upvotes: 3
Reputation: 16037
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())
Upvotes: 1