3

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);
    }
}
0

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

The answer provided by @Andy Turner looks wonderful. Here I just provide alternative solution by abacus-common.

List<String> strList = N.asList("a", "b", "c", "d");
List<String> result = Stream.of(strList).split(2).map(e -> e.join(" ", "(", ")")).toList();
N.println(result); // [(a b), (c d)]

strList = N.asList("a", "b", "c", "d", "e");
result = Stream.of(strList).split(2).map(e -> e.join(" ", "(", ")")).toList();
N.println(result); // [(a b), (c d), (e)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.