2

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>.

6
  • Works for me. Are you sure the error is caused by that line? Commented Jun 4, 2016 at 8:05
  • 2
    Are you using Eclipse? Googling the error message suggests that this is a bug with the Eclipse compiler. Commented Jun 4, 2016 at 8:15
  • @binoternary Yeah, I'm using Eclipse. When will this bug be fixed? Commented Jun 4, 2016 at 8:30
  • I don't use Eclipse myself so I'm not sure, but this seems to be the relevant bug bugs.eclipse.org/bugs/show_bug.cgi?id=480075. It's marked 'fixed' so maybe you just need to update Eclipse. Commented Jun 4, 2016 at 8:38
  • My Eclipse(Version: Mars.2 Release (4.5.2) Build id: 20160218-0600) pretends to be uptodate and has still the bug, as the fix date is after 20160218. Commented Jun 4, 2016 at 9:53

1 Answer 1

2

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));
}
Sign up to request clarification or add additional context in comments.

2 Comments

As soon as I save your line in eclipse (which I have to compile it) eclipse removes (String) and comes up again with Type mismatch: cannot convert from Stream<Object> to <unknown>. Maybe that's because I'm using AutoFormat on save.
its the option 'remove unnecessary casts', there are some parts of Eclipse smarter than the others :-)

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.