patternjavaMinor
Sorting colors by the name of the color
Viewed 0 times
sortingthecolorcolorsname
Problem
I was in need to sort
But unfortunately
Now let me know if this code can be improved and optimized.
Colors, so the first thing that I tried was this:Arrays.sort(new javafx.scene.paint.Color[] {Color.ALICEBLUE},Color.AZURE,Color.BLUEVIOLET,Color.AQUA,...);But unfortunately
Arrays.Sort is not compatible with javafx.scene.paint.Color, so I ended up with this:public static void main(String[] args) {
final String[] colors = {"AQUA", "LAWNGREEN", "LIGHTBLUE", "CYAN", "CHOCOLATE", "GREEN",
"RED", "YELLOW", "GAINSBORO", "YELLOWGREEN"};
final Function valueMapper = (final String name) -> {
try {
return (Color) Color.class.getField(name).get(null);
} catch (final IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e) {
throw new RuntimeException(e);
}
};
final Map map = Arrays.stream(colors).collect(
Collectors.toMap(Function.identity(), valueMapper));
map.entrySet().stream().sorted(Comparator.comparing(Entry::getKey)).forEach((Entry entry) -> {
System.out.println(entry.getKey() + " = " + entry.getValue());
});
}Now let me know if this code can be improved and optimized.
Solution
I like your approach with mapping function, but sorting alphabetically the collection of javafx.scene.paint.Color objects can be done a little bit easier:
as you can see the algorithm quite simple:
final String[] colors = {"AQUA", "LAWNGREEN", "LIGHTBLUE", "CYAN", "CHOCOLATE", "GREEN",
"RED", "YELLOW", "GAINSBORO", "YELLOWGREEN"};
Stream.of(colors).sorted().map(color -> Color.web(color)).forEach(System.out::println);as you can see the algorithm quite simple:
- Sort the string array
- Map string to Color object using API method
Code Snippets
final String[] colors = {"AQUA", "LAWNGREEN", "LIGHTBLUE", "CYAN", "CHOCOLATE", "GREEN",
"RED", "YELLOW", "GAINSBORO", "YELLOWGREEN"};
Stream.of(colors).sorted().map(color -> Color.web(color)).forEach(System.out::println);Context
StackExchange Code Review Q#98125, answer score: 2
Revisions (0)
No revisions yet.