我尝试在HashMap中找到具有最高值的查找键<字符串,双>使用lambdaj。 我猜选择Max()会有所帮助,但在这种情况下我不知道如何使用它。
答案 0 :(得分:3)
我已经下载了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]
答案 1 :(得分:1)
java.util.HashMap <String,Double> map;
java.util.Map.Entry<String,Double> entry;
double maxx = selectMax(map, on(entry.getClass()).getValue())
答案 2 :(得分:0)
/**
* @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));
}
}