javafunctional-programmingdeclarative-programming

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

Solution

  • Here, try this.

            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]