I am learning how to use Java 8 streams. How can I do the following using streams instead of a for loop:
public static void clump(ArrayList strList)
{
for(int i = 0; i < strList.size() - 1; i++)
{
String newStr = "(" + strList.get(i) + " "
+ strList.get(i + 1) + ")";
strList.set(i, newStr);
strList.remove(i + 1);
}
}
Use an IntStream between 0 and half the list's size, and multiply the elements by 2:
List<String> joined =
IntStream.range(0, strList.size() / 2)
.mapToObj(i -> "(" + strList.get(2*i) + " "
+ strList.get(2*i + 1) + ")")
.collect(Collectors.toList());
This puts the joined elements into a new list. To get rid of the un-joined elements from the original list, and prepend the joined elements, we can use a subList, which is a mutable view of the list:
List<String> subList = strList.subList(0, strList.size() / 2 * 2);
subList.clear();
subList.addAll(joined);
Ideone Demo
An alternative to the sublist stuff would be to handle the last element in the stream too:
List<String> joined =
IntStream.range(0, (1 + strList.size()) / 2)
.mapToObj(i ->
(2*i + 1) < strList.size()
? "(" + strList.get(2*i) + " " + strList.get(2*i + 1) + ")"
: strList.get(2*i))
.collect(Collectors.toList());
Ideone demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With