簡體   English   中英

計算Java中每小時發生的次數

[英]count the number of occurences for each hour in Java

首先,對不起我的英語(可能會很差),希望您能理解我

我看不到如何每小時恢復我的對象計數。 希望您能幫助我找到有關我的問題的更多信息。

我有一個任務對象 ,其中包含一個任務列表 ,每個任務列表都有一個屬性STRING名稱STRING時間 (hhmmss格式)

這是一個例子:

0:名稱1 102101

1:名稱2 102801

2:名稱3 104801

3:名稱4 110501

4:名稱5 120301

我希望我可以做一個數組,讓我計算每個小時的任務數量

在這個例子中,我將有:

10 => 3

11 => 1

12 => 1

我不知道你是否明白我想要得到的東西:)

如果您有小路,我會感興趣

感謝您閱讀我!

祝你晚上好

TL; DR

  • 正如評論所說,你可能想使用一個HashMap具有String鍵反映小時 Integer計數 (每小時任務)。
  • 由於您要處理小時,也就是說您最多有24個小時,因此您也可以將HashMap替換為24個項目的Array

Mission

基本上,所有在這里需要的是對A 吸氣 time屬性。 如果您覺得不錯,還可以添加getHour ,它將返回小時而不是整個time字符串。

class Mission {
    private String name;
    private String time;
    Mission(String name, String time) {
        this.name = name;
        this.time = time;
    }

    String getHour() {
        // This gives us the 2 first characters into a String - aka the "hour"
        return time.substring(0, 2);
    }
}

使用HashMap

我們希望將每小時計數保留在HashMap 因此,我們將遍歷missionsList並為每個項目獲取其count ,然后對其進行遞增。

如果hour尚未在HashMap ,我們通常會收到null 為了以最少的樣板處理此問題,我們將使用getOrDefault方法。 我們可以這樣稱呼它map.getOrDefault("10", 0) 這將返回任務第10小時的計數 ,如果該計數尚不存在(這意味着我們尚未將其添加到地圖中),我們將收到0而不是null 該代碼將如下所示

public static void main(String[] args) {
    // This will built our list of missions
    List<Mission> missionsList = Arrays.asList(
            new Mission("name1", "102101"),
            new Mission("name2", "102801"),
            new Mission("name3", "104801"),
            new Mission("name4", "110501"),
            new Mission("name5", "120301")
    );

    // This map will keep the count of missions (value) per hour (key)
    Map<String, Integer> missionsPerHour = new HashMap<>();

    for (Mission mission : missionsList) {
        // Let's start by getting the hour,
        // this will act as the key of our map entry
        String hour = mission.getHour();

        // Here we get the count of the current hour (so far).
        // This is the "value" of our map entry
        int count = missionsPerHour.getOrDefault(mission.getHour(), 0);

        // Here we increment it (by adding/replacing the entry in the map)
        missionsPerHour.put(hour, count + 1);
    }

    // Once we have the count per hour,
    // we iterate over all the keys in the map (which are the hours).
    // Then we simply print the count per hour
    for (String hour : missionsPerHour.keySet()) {
        System.out.println(String.format(
            "%s\t=>\t%d", hour, missionsPerHour.get(hour)
        ));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM