Using the List API we can leverage the subList method as well as the addAll method to modify a particular section of a list and insert elements into a list at the specified position.
Along with that, we utilise the String replace method to remove the redundant string representation of a list and finally convert the accumulator list into an array of strings.
public static String[] concatElements(String[] elements, int start, int count){
List<String> accumulator = new ArrayList<>(Arrays.asList(elements));
List<String> subList = new ArrayList<>(accumulator.subList(--start, start + count));
accumulator.removeAll(subList);
String concatenatedElements = subList.toString()
.replace(",", "")
.replace("[","")
.replace("]", "");
subList = Collections.singletonList(concatenatedElements);
accumulator.addAll(start, subList);
String[] resultSet = new String[accumulator.size()];
for (int i = 0; i < accumulator.size(); i++) {
resultSet [i] = accumulator.get(i);
}
return resultSet;
}
calling it like so:
System.out.println(Arrays.toString(concatElements(array, 2, 2)));
will produce:
[europe, france germany, america]
and calling it like so:
System.out.println(Arrays.toString(concatElements(array, 2, 3)));
will produce:
[europe, france germany america]
As is, there is no validation for the parameter start and count but I leave that as an exercise for you.
xandyvalues translate into various concatenations.x=2,y=2, that means starting from the 2 nd element, concatenate, until we have concatenated 2 elements