将 SortedSet 转换为 TreeMap 或 ImmutableMap,并将键作为迭代器位置

我有一个SortedSet<MyObject>并且MyObject有一些compareTo逻辑Date。


class MyObject {

   .. many fields

   private Date date;


   @Override

    public int compareTo(MyObject object) {

    .. logic here..

    }    


}

我想将其转换SortedSet为 aTreeMap或 Guava 的ImmutableSortedMap键作为 中元素的位置SortedSet。


例如


0 -> MyObject1

1 -> MyObject2

...and so on

我可以迭代并手动SortedSet将元素放入新元素中TreeMap,但我想知道是否有更干净的方法可以通过 Streams 或 Guava 库/Collection 库来完成。


叮当猫咪
浏览 77回答 3
3回答

月关宝盒

只要用循环来做就可以了。TreeMap<Integer, MyClass> map = new TreeMap<>();for (MyClass myClass : sortedSet) {  map.put(map.size(), myClass);}

POPMUISE

使用流外部的有效最终计数器变量。由于插入是按顺序进行的,因此您不需要最终的映射是TreeMap; 它可以更快LinkedHashMap,其迭代顺序与插入相同。AtomicInteger counter = new AtomicInteger();Map<Integer, MyClass> map = sortedSet.stream()&nbsp; .collect(Collectors.toMap(&nbsp; &nbsp; x -> counter.getAndIncrement(),&nbsp; &nbsp; x -> x,&nbsp; &nbsp; (a, b) -> a,&nbsp; &nbsp; LinkedHashMap::new));如果您迫切需要一个TreeMap,请在上面的代码中替换LinkedHashMap为。TreeMap

慕神8447489

您的 TreeMap 想法不正是数组吗?MyObject[]&nbsp;myObjects&nbsp;=&nbsp;sortedMap.toArray();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java