为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

叮当猫咪 2023-12-30 15:59:35
我有一个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 -> MyObject11 -> MyObject2...and so on我可以迭代并手动SortedSet将元素放入新元素中TreeMap,但我想知道是否有更干净的方法可以通过 Streams 或 Guava 库/Collection 库来完成。
查看完整描述

3 回答

?
月关宝盒

TA贡献1772条经验 获得超5个赞

只要用循环来做就可以了。


TreeMap<Integer, MyClass> map = new TreeMap<>();

for (MyClass myClass : sortedSet) {

  map.put(map.size(), myClass);

}

查看完整回答
反对 回复 2023-12-30
?
POPMUISE

TA贡献1765条经验 获得超5个赞

使用流外部的有效最终计数器变量。


由于插入是按顺序进行的,因此您不需要最终的映射是TreeMap; 它可以更快LinkedHashMap,其迭代顺序与插入相同。


AtomicInteger counter = new AtomicInteger();

Map<Integer, MyClass> map = sortedSet.stream()

  .collect(Collectors.toMap(

    x -> counter.getAndIncrement(),

    x -> x,

    (a, b) -> a,

    LinkedHashMap::new));

如果您迫切需要一个TreeMap,请在上面的代码中替换LinkedHashMap为。TreeMap


查看完整回答
反对 回复 2023-12-30
?
慕神8447489

TA贡献1780条经验 获得超1个赞

您的 TreeMap 想法不正是数组吗?

MyObject[] myObjects = sortedMap.toArray();


查看完整回答
反对 回复 2023-12-30
  • 3 回答
  • 0 关注
  • 69 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信