Reputation: 63
import java.util.Arrays;
import java.util.List;
public class CapitalizeAndSort {
public static void main(String[] args) {
List<String> topNames2017 = Arrays.asList(
"Amelia",
"Olivia",
"emily",
"Isla",
"Ava",
"oliver",
"Jack",
"Charlie",
"harry",
"Jacob"
);
for(int i = 0; i < topNames2017.size(); i++) {
topNames2017.set(i, capitalize(topNames2017.get(i)));
}
List<String> sorted = Arrays.asList(
topNames2017.stream().sorted(
(s1, s2) -> s1.compareToIgnoreCase(s2)
).toArray(String[]::new)
);
sorted.forEach(System.out::println);
}
private static String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
}
The above code works and sorts it the way I want to.
How can I sort that alphabetically and making sure the first letter is capitalized using method references?
Help is greatly appreciated!
Upvotes: 1
Views: 3658
Reputation: 54659
It is not entirely clear whether you really want the case insensitive order, or whether capitalizing the strings and then sorting them (case-sensitively) would be sufficient, but the difference should not be important.
You asked
How can I sort that alphabetically and making sure the first letter is capitalized using method references?
In order to use the reference for the capitalize
method, you have to use the YourClassName
::capitalize
syntax.
An example is shown below:
Stream
of names from the given listcapitalize
methodString.CASE_INSENSITIVE_ORDER
if this didn't matter)List<String>
The full code:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CapitalizeAndSort {
public static void main(String[] args) {
List<String> topNames2017 = Arrays.asList(
"Amelia",
"Olivia",
"emily",
"Isla",
"Ava",
"oliver",
"Jack",
"Charlie",
"harry",
"Jacob"
);
List<String> sorted = topNames2017.stream()
.map(CapitalizeAndSort::capitalize)
.sorted(String.CASE_INSENSITIVE_ORDER)
.collect(Collectors.toList());
sorted.forEach(System.out::println);
}
private static String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
}
Upvotes: 0
Reputation: 161
You can sort alphabetically writing like below:
Collections.sort(topNames2017, String.CASE_INSENSITIVE_ORDER);
and make first letter capitalized writing like below:
topNames2017 = topNames2017.substring(0, 1).toUpperCase() + topNames2017.substring(1);
Upvotes: 1