99.3k views
10 votes
Write a program called clump that accepts an ArrayList of strings as a parameter and replaces each pair of strings with a single string that consists of the two original strings in parentheses separated by a space. If the list is of odd length, the final element is unchanged. For example, suppose that a list contains

1 Answer

9 votes

Answer:

In Java:

public static void clump(ArrayList<String> MyList) {

for(int i = 0; i<MyList.size()-1;i++){

String newStr = "(" + MyList.get(i) + " "+ MyList.get(i + 1) + ")";

MyList.set(i, newStr);

MyList.remove(i + 1);

}

System.out.println("Updated ArrayList: " + MyList);

}

Step-by-step explanation:

First, we define the method

public static void clump(ArrayList<String> MyList) {

Next, we iterate through the ArrayList

for(int i = 0; i<MyList.size()-1;i++){

This clumps/merges every other ArrayList element

String newArr = "(" + MyList.get(i) + " "+ MyList.get(i + 1) + ")";

This updates the elements of the ArrayList

MyList.set(i, newArr);

This removes ArrayList elements at odd indices (e.g. 1,3...)

MyList.remove(i + 1);

}

This prints the updated List

System.out.println("Updated ArrayList: " + MyList);

}

User Pavan
by
4.8k points