Java Reference
In-Depth Information
< Day Day Up >
Puzzle 60: One-Liners
Now it's your turn to write some code. Each of the following puzzles can be solved with a method
whose body contains but a single line. On your mark, get set, code!
A.
Write a method that takes a List of elements and returns a new List containing the same
elements in the same order with the second and subsequent occurrences of any duplicate
elements removed. For example, if you pass in a list containing "spam" , "sausage" , "spam" ,
"spam" , "bacon" , "spam" , "tomato" , and "spam" , you'll get back a new list containing " spam ",
" sausage ", " bacon ", and " tomato ".
B.
Write a method that takes a string containing zero or more tokens separated by commas and
returns an array of strings representing the tokens in the order they occur in the input string.
Each comma may be followed by zero or more white space characters, which must be ignored
by the method. For example, if you pass the string "fear, surprise, ruthless
efficiency, an almost fanatical devotion to the Pope, nice red uniforms" , you'll
get back a five-element string array containing "fear" , "surprise" , "ruthless efficiency" ,
"an almost fanatical devotion to the Pope" , and "nice red uniforms" .
C.
Suppose that you have a multidimensional array that you want to print for debugging
purposes. You don't know how many levels the array has or what type of objects are stored at
each level in the array. Write a method that shows you all the elements at each level.
D.
Write a method that takes two int values and returns TRue if the first value has more bits set
than the second in its two's-complement binary representation.
Solution 60: One-Liners
A.
It is well known that you can eliminate all the duplicate elements in a collection by putting its
contents into a Set . In this puzzle, you were also asked to preserve the order of the original
collection. Luckily, there is a Set implementation that maintains its elements in insertion
order, and it offers near- HashMap performance to boot. It's called LinkedHashSet , and it was
added to the platform in release 1.4. Internally, it is implemented as a hash table with a linked
list running through it. There is also a map version that you can use to make custom caches.
Once you know about LinkedHashSet , it's easy to solve this puzzle. The only other wrinkle is
that you were asked to return a List , so you have to initialize a List with the contents of the
LinkedHashSet . Putting it all together, here is the solution:
static <E> List<E> withoutDuplicates(List<E> original) {
return new ArrayList<E>(new LinkedHashSet<E>(original));
 
 
Search WWH ::




Custom Search