I was in need to sort 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",

    final Function<String, ? extends Color> 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<String, Color> map = Arrays.stream(colors).collect(
            Collectors.toMap(Function.identity(), valueMapper));

    map.entrySet().stream().sorted(Comparator.comparing(Entry::getKey)).forEach((Entry<String, Color> entry) -> {
        System.out.println(entry.getKey() + " = " + entry.getValue());


Now let me know if this code can be improved and optimized.

  • \$\begingroup\$ Arrays has sort(Object[]) and sort(T[], Comparator<? extends T>). Your attempt shows you creating an array with 1 element, then a bunch of colors, as if sort was sort(T[], T...) or sort(T[], T, T, T). Notice your Color[] { Color.ALICEBLUE }, Color.AZURE, Color.BLUEVIOLET, Color.AQUA, when it should be Color[] { Color.ALICEBLUE, Color.AZURE, Color.BLUEVIOLET, Color.AQUA } \$\endgroup\$
    – Dioxin
    Jul 27, 2015 at 0:00
  • \$\begingroup\$ I am having trouble understanding what you're doing here. Are you sorting by colour (i.e. physical colour) or name, or something entirely different? \$\endgroup\$
    – insidesin
    Jul 27, 2015 at 15:53

1 Answer 1


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:

    final String[] colors = {"AQUA", "LAWNGREEN", "LIGHTBLUE", "CYAN", "CHOCOLATE", "GREEN",

    Stream.of(colors).sorted().map(color -> Color.web(color)).forEach(System.out::println);

as you can see the algorithm quite simple:

  1. Sort the string array
  2. Map string to Color object using API method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.