我试图找到在HashMap中具有最高值的查找键<String,Double>使用lambdaj。我想selectMax()会有帮助,但我不知道如何使用它在这种情况下
我下载了lambdaj并尝试了一下。给你
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)))))
);
}
}
打印出[2s3.5=3.5, s3.5=3.5]
你试过吗?
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;
}
和一个测试:
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));
}
}