Java List merge two element
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<String> lang = Arrays.asList(new String[] { "CSS", "HTML", "C++", "Java" }); System.out.println(lang); /*from w w w .j a v a 2 s. co m*/ System.out.println(lang.size()); lang = merge(lang, 1); System.out.println(lang); System.out.println(lang.size()); } 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; } } }