【问题标题】:What's a more functional way in Java 8 of updating items in a list with their index?Java 8 中使用索引更新列表中项目的更实用的方法是什么?
【发布时间】:2018-07-12 01:02:05
【问题描述】:

给定:

  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);
  }

在 Java 8 中,在“功能化我”cmets 之间编写代码的更实用的方法是什么?我正在考虑使用 reduce 或 collect 的策略,但在我的脑海中看不到解决方案。

【问题讨论】:

标签: java-8 functional-programming


【解决方案1】:

您不应假设Collectors.toList() 返回的列表是可变的。因此,您不得在其上调用sort。在您的具体情况下,您可以在收集之前进行排序:

List<Item> items = Stream.of("z", "y", "x")
  .map(Item::new)
  .sorted(Comparator.comparing(o -> o.name))
  .collect(Collectors.toList());

或者,因为name 与传入的字符串相同:

List<Item> items = Stream.of("z", "y", "x")
  .sorted()
  .map(Item::new)
  .collect(Collectors.toList());

然后,您可以使用更新列表项

IntStream.range(0, items.size()).forEach(i -> items.get(i).index = i);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-20
    • 2021-05-22
    • 2023-02-05
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    相关资源
    最近更新 更多