0
var numbers = new ArrayList<Integer>(100);
for (var i = 1; i <= 100; i++) {
    numbers.add(i);
}

This is a series of numbers (just for example) But, it starts with the wrong number. I need it to start with 21, not 1. Modifying the cycle would be unnecessarily complex. It is easier to divide the ArrayList into two List and swap them.

numbers = Stream.concat(numbers.subList(20, 100).stream(), numbers.subList(0, 20).stream()).collect(Collectors.toCollection(ArrayList::new));

I used the concat method, which merges two ArrayLists and subList method, which returns a part of the ArrayList.

However, it is illogical to create a new ArrayList that is only differently ordered.

It would be enough to use the sorted method, but I don't know how to write it to sort it correctly.

Please help

Thank you

Michal Rama
  • 173
  • 1
  • 1
  • 10
  • I cannot make any sense of your Question. If you want loop to start at 21, change `i = 1` to `i = 21`. If you want to split an ArrayList, that has been covered many times already on Stack Overflow. If you want to sort the List, that too has been covered many many times already. But I have no idea *what* you really want. Voting to close as unclear. – Basil Bourque Sep 15 '19 at 15:17
  • Why the JavaFX tag? – Basil Bourque Sep 15 '19 at 15:18
  • Duplicate: [*Sorting a list with stream.sorted*](https://stackoverflow.com/questions/40517977/sorting-a-list-with-stream-sorted-in-java) – Basil Bourque Sep 15 '19 at 15:20
  • @Basil Bourque I deleted the tag. Yes, you are right. I just didn't know what to look for. Only when writing the question did I realize that I should use the `sorted` method. However, the @Udith Gunaratna user stated exactly what I wanted. – Michal Rama Sep 15 '19 at 16:32

1 Answers1

2

Basically in sorting comparator, you get 2 numbers (let's say n1 and n2), and based on the return value, they will be ordered.

  • If a negative value is returned, n1 is ordered before n2
  • If a positive value is returned, n2 is ordered before n1
  • If 0 is returned, both are considered equal in order

Keeping this in mind, you can write the sorting comparator to provide the following behavior.

  • If both n1 and n2 are in the same region (either between 0-19 or 20-100), sort them as usual
  • If n1 and n2 are in different regions, order the number belongs to the 20-100 (which will be the larger number of the two) before the other one

Example code,

numbers =
    (ArrayList<Integer>)
            numbers.stream()
                    .sorted((n1, n2) -> {
                        if (((n1 >= 21) && (n2 >= 21)) || ((n1 <= 20) && (n2 <= 20))) {
                            return  n1 - n2;
                        } else {
                            return n2 - n1;
                        }
                    }).collect(Collectors.toList());
Udith Gunaratna
  • 2,091
  • 1
  • 13
  • 17