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

143 Views Asked by At

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

There are 2 best solutions below

0
WJS On BEST ANSWER

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]
1
Lajos Arpad On

You can do it with the following one-liner:

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