我想写一个比较器,让我按值而不是默认的自然顺序对TreeMap进行排序.
我试过这样的东西,却找不到出了什么问题:
import java.util.*;
class treeMap {
public static void main(String[] args) {
System.out.println("the main");
byValue cmp = new byValue();
Map<String, Integer> map = new TreeMap<String, Integer>(cmp);
map.put("de",10);
map.put("ab", 20);
map.put("a",5);
for (Map.Entry<String,Integer> pair: map.entrySet()) {
System.out.println(pair.getKey()+":"+pair.getValue());
}
}
}
class byValue implements Comparator<Map.Entry<String,Integer>> {
public int compare(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2) {
if (e1.getValue() < e2.getValue()){
return 1;
} else if (e1.getValue() == e2.getValue()) {
return 0;
} else {
return -1;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想我要问的是:我可以Map.Entry传递给比较器吗?
如果LinkedHashMap包含String和Integer,我如何根据其值对LinkedHashMap进行排序.所以我需要根据整数值对它进行排序.非常感谢
示例程序:
public final class CollectorTest
{
private CollectorTest()
{
}
private static <T> BinaryOperator<T> nope()
{
return (t, u) -> { throw new UnsupportedOperationException("nope"); };
}
public static void main(final String... args)
{
final Collector<Integer, ?, List<Integer>> c
= Collector.of(ArrayList::new, List::add, nope());
IntStream.range(0, 10_000_000).boxed().collect(c);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,为了简化这里的问题,没有最终的转换,因此生成的代码非常简单.
现在,IntStream.range()生成一个顺序流.我只是将结果打成Integers然后我的设计Collector将它们收集到一个List<Integer>.很简单.
无论我运行多少次这个示例程序,UnsupportedOperationException从不命中,这意味着我的虚拟组合器永远不会被调用.
我有点期待这个,但后来我已经误解了流,我不得不问这个问题......
可以在Collector当流的组合曾经被称为保证是连续的?