-2

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));
}
  • Shift where? Why don't you want to use `for` loop? Are you fine using `while` loop? You need to mention all these important points when you post a question. – Arvind Kumar Avinash Apr 16 '20 at 16:55
  • In addition to Arvind Kumar Avinash comment, if you can, please clarify why you need to shift elements that are stored in a list. You delete the first one? Someone might have a better solution an you may don't even have to shift them. – Kostas Thanasis Apr 16 '20 at 17:05
  • You want to shift to the right the list and after substitute the element at index 0 with the old first element of the list like [2, 3, 4, 5] -> [2, 2, 3, 4] ? – dariosicily Apr 16 '20 at 17:09
  • I wont modify the first element. I was looking for a declarative approach using Java 8 –  Apr 16 '20 at 17:19

2 Answers2

0

You can do it with the following one-liner:

(items = Arrays.asList(items.get(0))).addAll(items);
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
0

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]
WJS
  • 36,363
  • 4
  • 24
  • 39