简体   繁体   English

计算Java中按字段分组的对象

[英]Count objects grouping by field in Java

I have a class Flight and class for Airport which holds collection with several flights. 我有一个班机,一个有几个班机集合的机场班。

public class Flight {

String flightNumber;            
String departureCity;
String departureCountry;
String departure;
String arrivalCity;
String arrivalCountry;
String arrival;
//etc...}

public class Airport {

String name;
String city;
String country;
LinkedList <Flight> flights;
//etc...}

I have a task in university to count the number of flights in one airport for each departureCountry field of Flight class. 我在大学里有一项任务,要为每个FlightCountry航班类别的字段计算一个机场的航班数量。 Is there any algorithm to do that? 有什么算法可以做到吗? I thought to sort the collection somehow by this parameter(departureCountry) but couldn't come up with some clear decision. 我本来想通过此参数(departureCountry)对集合进行排序,但无法做出明确的决定。 I will be grateful for your help. 感谢您的帮助。

I'm not going to write the whole code here, but just the steps. 我不会在这里编写整个代码,而只是编写步骤。

  • for each airport 每个机场
    • keep a map of departureCountry to count (ie a map<String, Integer>) 保留一张countingCountry的地图以进行计数(即地图<String,Integer>)
    • for each flight in the airport 对于机场中的每个航班
      • increment the count for the departureCountry in the map // that's it, you have the counts now 在地图中增加// detailCountry的计数//就这样,您现在有了计数

Sorting is not needed at all given that who just need the count, ie essentially grouping for which a map is sufficient as explained in the steps above. 考虑到谁只需要计数,根本就不需要排序,即本质上分组,如上面的步骤中所述,一个映射就足够了。

There is a neat way using Java 8 streams: 使用Java 8流有一种巧妙的方法:

import java.util.*;
import static java.util.stream.Collectors.*;

public class Main {
    public static void main(String[] args) {
        // I made constructor for departureCountry only to keep it simple
        List<Flight> flights = Arrays.asList(
          new Flight("USA"),
          new Flight("UK"),
          new Flight("CAN"),
          new Flight("USA"),
          new Flight("UK")
        );

        Map<String, Long> flightsPerCountry =
          flights.stream()
                 .collect(groupingBy(Flight::getDepartureCountry, counting()));


        System.out.println(flightsPerCountry);
        // {CAN=1, USA=2, UK=2}
    }
}

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

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