principal-ideal-domain
principal-ideal-domain

Reputation: 4276

Convert List<Integer> to String

I've got a sequence of integers (List<Integer>) and want to convert it to a string. I don't see why this code doesn't work:

sequence.stream().map(n -> n == 1 ? "+" : (n == -1 ? "-" : Integer.toString(n))).collect(Collectors.joining(","));

As you see, I want 1 to be represented as + and -1 as -.

I get the error message Type mismatch: cannot convert from Stream<Object> to <unknown>.

Upvotes: 2

Views: 956

Answers (1)

Turo
Turo

Reputation: 4914

EDIT

After reading the comment knowing that Java is alright:

Eclipse isn't aware of n == 1 ? "+" : (n == -1 ? "-" : Integer.toString(n))).toString() beeing a String.

sequence.stream().map(n -> (String)((n == 1 ? "+" : (n == -1 ? "-" : Integer.toString(n))))).collect(Collectors.joining(","))

works fine.

EDIT

if you extract it to a function, Eclipse knows its a String:

private static String format(Integer n) {
    return n == 1 ? "+" : (n == -1 ? "-" : Integer.toString(n));
}

Upvotes: 2

Related Questions