I want to convert those if-statements into a ternary operator expression, but I’ve been struggling since I haven’t had the need to use them that much. The code essentially replaces the characters ‘1’ with ‘i’, removes characters that are not letters, and also removes upper-case letters by enqueuing elements that don’t meet those conditions.
private static Iterable<Character> transformationA(Queue<Character> q) { Queue<Character> retq = new Queue<>(); for(Character c: q) { if(c.equals('1')) { retq.enqueue('i'); } if(Character.isLowerCase(c)) { retq.enqueue(c); } } return retq; }
Edit: thanks for your comments, code and suggestions.
Advertisement
Answer
Ternary operation does not fit
As commented, a ternary operation is not appropriate to your code. A ternary operation in Java is an expression, returning a result.
In your case, you do not have a “if x is true, return y, otherwise return z” situation. In your case you may enqueue an I
, or you may enqueue a lowercase letter, or you may do nothing (thereby ignoring that nth character).
Unicode code points
The char
type (and its Character
wrapper class) are legacy, essentially broken. As a 16-bit value, the char
type is incapable of representing even half of the characters defined in Unicode.
Instead use Unicode code point integer numbers.
- Pass in a collection of
int
orInteger
(orIntStream
) rather thanCharacter
objects. And actually, I would just pass in aCharSequence
(the interface forString
, etc.). - To see if the code point represents the character for the digit
1
, check for a code point number of49
(decimal), the ASCII/Unicode number for the digit1
:if( codePoint == 49 ) { … }
wherecodePoint
is anint
/Integer
. - For lowercase check, pass the code point integer:
if( Character.isLowerCase( codePoint ) ) { … }
.