[英]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
我不知道你是否明白我想要得到的东西:)
如果您有小路,我会感兴趣
感谢您阅读我!
祝你晚上好
HashMap
具有String
键反映小时 Integer
值计数 (每小时任务)。 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.