我尝试使用lambdaj在 HashMap < String,Double > 中找到具有最高值的查找键。我猜 selectMax() 会有所帮助,但我不知道在这种情况下如何使用它。
问问题
6837 次
3 回答
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]
于 2011-08-30T14:16:11.243 回答
1
你试过这个吗?
java.util.HashMap <String,Double> map;
java.util.Map.Entry<String,Double> entry;
double maxx = selectMax(map, on(entry.getClass()).getValue())
于 2011-08-29T19:19:41.200 回答
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));
}
}
于 2013-04-02T13:34:10.757 回答