首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Java 8中,用索引更新列表中的项的更有效的方法是什么?

在Java 8中,用索引更新列表中的项的更有效的方法是什么?
EN

Stack Overflow用户
提问于 2018-07-11 23:55:09
回答 0查看 40关注 0票数 0

给定:

代码语言:javascript
运行
复制
  static class Item {
    String name;
    int index;

    Item(String name) {
      this.name = name;
    }
  }

  @Test
  public void test() {
    List<Item> items =
        Arrays.stream(new String[] {"z", "y", "x"})
          .map(Item::new)
          .collect(Collectors.toList());
    items.sort(Comparator.comparing(o -> o.name));

    // begin functionalize me    
    int i = 0;
    for (Item it : items) {
      it.index = i++;
    }
    // end functionalize me

    assertEquals(0, items.get(0).index);
    assertEquals(1, items.get(1).index);
    assertEquals(2, items.get(2).index);
  }

在Java8中,在"functionalize me“注释之间编写代码的更实用的方式是什么?我正在考虑使用reduce或collect的策略,但在我的脑海中看不到解决方案。

EN

回答

页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51289753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档