How to simplify a lambda method that receives a list of integers and returns a string by adding a letter before the number?

Viewed 170

I wanted to simplify this method so that I didn't need an ArrayList, that is, that only with lambdas I could stream the list of integers, analyze who is even or odd, add their corresponding letter and concatenate in a string

public static String o1e3method(List<Integer> list) {
    List<String> n = new ArrayList<>(); 
    list.forEach(x -> {
        if (x % 2 == 0) {
            n.add("e" + x);
        }
        else {
            n.add("o" + x);
        }
    });
    return String.join(", ", n);
}

In other words, I wanted something that was something like this:

public static String o1e3b(List<Integer> list) {
    return list.stream()
        .map(Object::toString)
        .forEach(x -> {
            if (Integer.parseInt(x) % 2 == 0) {
                x = "e" + x;
            }
            else {
                x = "o" + x;
            }
        })
        .collect(Collectors.joining(", "));
}

but I can't do this because the forEach is a void method and doesn't return what to collect.

3 Answers

forEach is a terminal operation, which does not return Stream. You need an intermediate operation to transform your numbers and return transformed stream, which you will later collect.

Note, that you have a redundant mapping to String, which you simply do not need.

I would recommend:

public static String o1e3b(List<Integer> list) {
    return list.stream()
            .map(x -> x % 2 == 0 ? "e" + x : "o" + x)
            .collect(Collectors.joining(", "));
}

Just in case you are not familiar, see what is Ternary Operator, which I use as a body of the mapper function.

You can simply map to String as:

return list.stream()
            .map(x -> x % 2 == 0 ? "e" + x : "o" + x)
            .collect(Collectors.joining(", "));

You have the right idea, but instead of forEach, you should use map. Also note there's no reason to convert the integers to string and then parse them again:

public static String o1e3b(List<Integer> list) {
    return list.stream()
            .map(x -> {
                if (x %2 == 0) {
                    return "e" + x;
                } else {
                    return "o" + x;
                }
            })
            .collect(Collectors.joining(", "));
}
Related