String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" };
I have a simple array of planet names, and I want to undo every name that has been added to the array (rather than string order).
I keep struggling with lambda syntax:
Arrays.sort(planets, (first, second) -> new StringBuilder(first).reverse().toString()); System.out.println(Arrays.toString(planets));
I am currently getting:
Several markers on this line
- The
reverse() method in type StringBuilder not applicable to arguments (String) - Type mismatch: cannot convert from
String to int
Answer:
Thanks everyone for the suggestions ... asList made me close. I was still sorting wrong.
So, I need to find a way to make array.sort work because it was the destination (take array.sort and lambda it).
I pinged an instructor to ask for clarification here, but I'm running out of time.
Here is my work trying to save array.sort
// lambda expression , long to short System.out.println("5) Sorted by length (descending):"); Arrays.sort(planets, (first, second) -> second.length() - first.length()); System.out.println(Arrays.toString(planets)); // lambda expression , reverse the name , then sort in ascending order // hint use new StringBuilder(first).reverse().toString() to reverse the string System.out.println("6) Sorted in dictionary order of the reversed name (ascending)"); Arrays.sort(planets, (first, second) -> new StringBuilder(first).reverse().toString().compareTo(second)); System.out.println(Arrays.toString(planets)); // lambda expression , reverse the name , then sort in descending order System.out.println("7) Sorted in dictionary order of the reversed name (descending)"); Arrays.sort(planets, (first, second) -> new StringBuilder(second).reverse().toString().compareTo(first)); System.out.println(Arrays.toString(planets));
What I canβt figure out for me here for life is that all 3 expressions give me exactly the same result ... each of them gives me the original array, sorted the longest.
This is my result:
5) Sort by length (descending): [Neptune, Mercury, Jupiter, Uranus, Saturn, Venus, Earth, Mars]
6) Sorting in the dictionary the reverse name order (ascending) [Neptune, Mercury, Jupiter, Uranus, Saturn, Venus, Earth, Mars]
7) Sorting in the dictionary the reverse name order (descending) [Neptune, Mercury, Jupiter, Uranus, Saturn, Venus, Earth, Mars]