-2

Suppose I have one container that contain different colors of ballons

  • such as Red, Blue, Green, Red,Blue,Red, Blue, Green in this order,
  • now sort that baloon in such manner so Red baloon will be added first
  • then Blue baloon and last is Green balloons. Use the proper collection
  • 1
    Use a `List`. Call `List#sort(Comparator)`. Pass a `Comparator` that defines the ordering you described. If you already have some code, but you're having a _specific_ problem, then please demonstrate that problem with a [mre]. – Slaw Sep 25 '22 at 05:37
  • Always search Stack Overflow thoroughly before posting. – Basil Bourque Sep 25 '22 at 15:54

1 Answers1

0

Just make your colors an enum.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Balloons {
    enum Colors {RED, BLUE, GREEN}

    public static void main(String[] args) {
        List<Colors> list = new ArrayList<>();
        list.add(Colors.RED);
        list.add(Colors.BLUE);
        list.add(Colors.GREEN);
        list.add(Colors.RED);
        list.add(Colors.BLUE);
        list.add(Colors.RED);
        list.add(Colors.BLUE);
        list.add(Colors.GREEN);
        Collections.sort(list);
        System.out.println(list);
    }
}

Running above code outputs the following:

[RED, RED, RED, BLUE, BLUE, BLUE, GREEN, GREEN]

Alternatively, if your colors are strings, define an appropriate comparator.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class Balloons {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Red");
        list.add("Blue");
        list.add("Green");
        list.add("Red");
        list.add("Blue");
        list.add("Red");
        list.add("Blue");
        list.add("Green");
        Comparator<String> c = (s1, s2) -> {
            if ("Red".equals(s1)) {
                if ("Red".equals(s2)) {
                    return 0;
                }
                return -1;
            }
            else if ("Blue".equals(s1)) {
                if ("Red".equals(s2)) {
                    return 1;
                }
                else if ("Blue".equals(s2)) {
                    return 0;
                }
                return -1;
            }
            else {
                if ("Green".equals(s2)) {
                    return 0;
                }
                return 1;
            }
        };
        list.sort(c);
        System.out.println(list);
    }
}
Abra
  • 19,142
  • 7
  • 29
  • 41