Java Collection How to - Merge two items from a List into one








Question

We would like to know how to merge two items from a List into one.

Answer

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*w  ww . java  2  s .  c  om*/
public class Main {
  public static void main(String[] args) {
    final List<String> fruits = Arrays.asList(new String[] { "A", "B",
        "C", "D" });
    System.out.println(fruits); 
    System.out.println(merge(fruits, 1)); 

  }

  public static List<String> merge(final List<String> list, final int index) {
    if (list.isEmpty()) {
      throw new IndexOutOfBoundsException("Cannot merge empty list");
    } else if (index + 1 >= list.size()) {
      throw new IndexOutOfBoundsException("Cannot merge last element");
    } else {
      final List<String> result = new ArrayList<String>(list);
      result.set(index, list.get(index) + list.get(index + 1));
      result.remove(index + 1);
      return result;
    }
  }

}

The code above generates the following result.