【问题标题】:Method to count property of an Object linked to another property计算链接到另一个属性的对象的属性的方法
【发布时间】:2021-02-16 19:56:48
【问题描述】:

假设我有一个文件,其中包含多个平面和有关平面结构的信息:

type,max speed,name,color
commercial plane,750,boeing_777,white
private jet,800,cynthia,blue
propeller plane,200,venus,yellow
commercial plane,640,boeing_737,white
commercial plane,550,airbus,blue
propeller planes,150,tatoo,yellow
private jet,670,VLJ, white

由此我创建了 Planes 类

public Planes{
    static int counter = 1;

    String type;
    int maxSpeed;
    String name;
    String color;
    int id;

    public Planes(List<String> element) {

        this.type = element.get(0)
        this.maxSpeed = element.get(1)
        this.name = element.get(2)
        this.color = element.get(3)
        this.id = counter;
        counter++;
}

我做了几个方法,现在我的 Planes 类型的对象在一个 ArrayList 中 我的目标是输出一个字符串,用于打印类型和平面类型具有的不同颜色的数量。所以输出将是:

commercial plane,2 //2 because it has both white and blue NOT 3
private jet,2
propeller plane,1

我尝试了以下方法:


for (int i = 0; i < arrayListPlanes.size(); ++i) {

        int it = 0;
        newList.add(arrayListPlanes.get(i).getColor());
        if(newList.contains(arrayListPlanes.get(i).getColor())) {
                it = it + 1;
            }

        String line += arrayListPlanes.get(i).type() + ", " +
                      Collections.frequency(newList, arrayListPlanes.get(i).getColor()) +
                      "\n";
}

实际列表要长得多,并且包含多种其他类型的飞机,因此我无法为每种类型的飞机制作一个对象。
我为写得不好的标题道歉

【问题讨论】:

    标签: java object arraylist


    【解决方案1】:

    按类型对平面进行分组,然后收集颜色集并重新映射到颜色集的大小就可以了:

    static void countPlaneColorsByType(List<Plane> planes) {
        planes.stream()
          .collect(Collectors.groupingBy(p -> p.type, LinkedHashMap::new, Collectors.mapping(p -> p.color, Collectors.toSet())))
          .entrySet().stream()
          .map(e -> new StringBuilder(e.getKey()).append(": ").append(e.getValue().size()))
          .forEach(System.out::println);
    }
    

    不过,Planes 类有几点需要修复:

    • 重命名为Plane,因为它描述了一个平面
    • 修复编译问题
    public static class Plane{
        static int counter = 1;
    
        String type;
        int maxSpeed;
        String name;
        String color;
        int id;
    
        public Plane(List<String> element) {
    
            this.type = element.get(0);
            this.maxSpeed = Integer.parseInt(element.get(1));
            this.name = element.get(2);
            this.color = element.get(3);
            this.id = counter;
            counter++;
        }
    }
    

    测试

    public static void main(String...args) {
        List<Plane> planes = Arrays.asList(
            new Plane(Arrays.asList("commercial plane", "750", "boeing_777", "white")),
            new Plane(Arrays.asList("private jet", "800", "cynthia", "blue")),
            new Plane(Arrays.asList("propeller plane", "200", "venus", "yellow")),
            new Plane(Arrays.asList("commercial plane", "640", "boeing_737", "white")),
            new Plane(Arrays.asList("commercial plane", "550", "airbus", "blue")),
            new Plane(Arrays.asList("propeller plane", "150", "tatoo", "yellow")),
            new Plane(Arrays.asList("private jet", "670", "VLJ", " white"))
        );
        
        countPlaneColorsByType(planes);
    } 
    

    输出

    commercial plane: 2
    private jet: 2
    propeller plane: 1
    

    【讨论】:

      【解决方案2】:

      这是基于 Stream API 的简单解决方案:

      // Group all planes by type
      // key is plane type, value is list of planes
      Map<String, Set<Planes>> plainsByType = planes.stream()
                      .collect(Collectors.groupingBy(p -> p.type));
      plainsByType.entrySet().stream()
          .map(e -> String.format("%s, %d", e.getKey(), countOfUniqueColors(e.getValue())))
          .forEach(System.out::println);
      
          long countOfUniqueColors(Set<Planes> planes) {
              return planes.stream().map(p -> p.color).distinct().count();
          }
      

      【讨论】:

        【解决方案3】:

        您可以在此处使用 HashMap 来获取 newList,如下所示:

        Map<Color,Interger> newList = new HashMap();
        int it = 0;
        if( newList.containsKey(color) )
        {
            it = newList.get(color).value();
        }
        

        它++; newList.put(color, it);

        【讨论】:

          猜你喜欢
          • 2017-06-07
          • 2016-07-18
          • 2020-05-17
          • 2020-06-22
          • 2015-09-20
          • 2022-06-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多