简体   繁体   中英

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? 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]

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. (the reason for the new ArrayList<>() call)
  • rotates left 1 item.
        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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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