简体   繁体   English

使用声明性方法来移动 ArrayList 元素,而不是使用循环

[英]Use declarative approach to shift ArrayList elements instead of using a loop

Could you please point out a way to shift the elements of the list below, without using a for loop?您能否指出一种在不使用 for 循环的情况下移动下面列表元素的方法? Please note that the first element of the list is not affected by the operation performed.请注意,列表的第一个元素不受所执行操作的影响。 From [2, 3, 4, 5] the list would become [2, 2, 3, 4]从 [2, 3, 4, 5] 列表将变为 [2, 2, 3, 4]

List<BigDecimal> items = Arrays.asList(new BigDecimal(2), new BigDecimal(3), new BigDecimal(4), new BigDecimal(5));
for (int i = items.size() - 1; i >= 1; i--) {
    items.set(i, items.get(i - 1));
}

You can do it with the following one-liner:您可以使用以下单线来做到这一点:

(items = Arrays.asList(items.get(0))).addAll(items);

Here, try this.来,试试这个。

  • requires subList method.需要 subList 方法。 (the reason for the new ArrayList<>() call) (新的 ArrayList<>() 调用的原因)
  • rotates left 1 item.向左旋转 1 个项目。
        List<BigDecimal> items = new ArrayList<>(
                Arrays.asList(new BigDecimal(2), new BigDecimal(3),
                        new BigDecimal(4), new BigDecimal(5)));
        List<BigDecimal> list = items.subList(1, items.size());
        list.add(items.get(0));
        System.out.println(list);

Prints印刷

[3, 4, 5, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM