简体   繁体   English

如何解决通过collection对不同球进行排序

[英]How to solve sorting of different balls by collection

Suppose I have one container that contain different colors of ballons假设我有一个包含不同 colors 气球的容器

  • 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使用正确的集合

Just make your colors an enum .只需将您的colors 设为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.或者,如果您的colors是字符串,请定义一个适当的比较器。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM