如何从自定义类为键的TreeMap中筛选并打印指定枚举颜色的对象
解决方案
1. 确保枚举类正确返回目标颜色集合
首先确认你的枚举类(假设名为Color)中,返回非黑白颜色的方法逻辑正确,示例代码如下:
public enum Color { BLACK, WHITE, GREEN, RED, YELLOW, BLUE; // 返回除Black、White外的所有颜色 public static Set<Color> getNonMonochromeColors() { // 方式1:直接指定目标颜色 return EnumSet.of(GREEN, RED, YELLOW, BLUE); // 方式2:通过排除法获取 // Set<Color> colors = EnumSet.allOf(Color.class); // colors.remove(BLACK); // colors.remove(WHITE); // return colors; } }
2. 自定义键类需提供颜色获取方法
你的自定义键类(示例为Plains)必须包含获取颜色的getter方法,同时因为是TreeMap的键,需要实现Comparable接口(或创建TreeMap时传入自定义比较器):
public class Plains implements Comparable<Plains> { private Color color; private String model; private int year; // 构造函数 public Plains(Color color, String model, int year) { this.color = color; this.model = model; this.year = year; } // 获取颜色的getter方法 public Color getColor() { return color; } // 重写toString,确保输出符合预期格式 @Override public String toString() { return String.format("Plains{color=%s, model='%s', year=%d}", color.name(), model, year); } // 实现Comparable接口,用于TreeMap排序 @Override public int compareTo(Plains o) { // 可根据需求调整排序逻辑,示例按颜色排序 return this.color.compareTo(o.color); } }
3. 遍历TreeMap并过滤打印
在主方法中,先获取枚举方法返回的目标颜色集合,再通过for循环遍历TreeMap的键,判断颜色是否符合条件,符合则打印:
import java.util.Set; import java.util.TreeMap; import java.util.EnumSet; public class Main { public static void main(String[] args) { TreeMap<Plains, Integer> colorMap = new TreeMap<>(); // 存入6个包含所有颜色的Plains对象 colorMap.put(new Plains(Color.BLACK, "Boing", 2020), 1); colorMap.put(new Plains(Color.WHITE, "Boing", 2020), 2); colorMap.put(new Plains(Color.GREEN, "Boing", 2020), 3); colorMap.put(new Plains(Color.RED, "Boing", 2020), 4); colorMap.put(new Plains(Color.YELLOW, "Boing", 2020), 5); colorMap.put(new Plains(Color.BLUE, "Boing", 2020), 6); // 获取需要打印的颜色集合 Set<Color> targetColors = Color.getNonMonochromeColors(); // 遍历并过滤打印 for (Plains plains : colorMap.keySet()) { if (targetColors.contains(plains.getColor())) { System.out.println(plains); } } } }
关键说明
- 使用
EnumSet存储枚举集合比普通HashSet更高效,是枚举类型集合的最优选择。 - TreeMap的键必须实现
Comparable接口或传入自定义Comparator,否则会抛出ClassCastException。 - 遍历
keySet()直接获取所有键对象,通过contains()方法快速判断颜色是否在目标集合中,即可得到预期输出。
内容的提问来源于stack exchange,提问作者Kiril Karpuhin
相关产品推荐
相关产品推荐

