Suppose I have an ArrayList<String> list that contains elements:

 [0] <название_пары_1> [1] <преподаватель_1> [2] <название_пары_2> [3] <преподаватель_2> 

We need to change the list so that we get the following.

 [0] <название_пары_1> <преподаватель_1> [1] <название_пары_2> <преподаватель_2> 

How to do it?

    3 answers 3

    If you want to change the original list, use the addition of lines and the method of removing an element from the list remove , which for convenience returns the value of the element to be deleted.

      // каким то образом получаем исходный список List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); // попарно суммируем элементы и удаляем ненужные, пока список не кончиться for (int i =0; i<list.size(); i++) { list.set(i, list.get(i) + list.remove(i+1)); } // смотрим результат System.out.println(list); 
    • For some reason, I expected that due to remove and size algorithm would break, but not :) - gil9red
    • list.size () is executed in each loop, i.e. the value of this field is updated with the resizing of the list. If you assign this value to a variable and check i <variable - then yes, it will break. - Mark

    The algorithm is as follows: 1. Create a new list. 2. Add to the zero cell of the new list the sum of the zero and first cells of the old list. 3. Repeat this action the necessary number of times for the next cell of the new list and each pair of cells of the old list.

      Steps:

      • Create a list
      • Iterating over the indexes of the first list in increments of 2
      • Add to the new list the concatenation of the current and the next element

      Code:

       List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); List<String> newList = new ArrayList<>(); for (int i = 0; i < list.size(); i += 2) { newList.add(list.get(i) + list.get(i + 1)); } System.out.println(newList); // [AB, CD]