一种方法是跟踪条目的数量并增加。
public static void main(String[] args)
{
String[] inp = {"1112323 400 error",
"1112323 400 error",
"9988778 400 error"};
Map<String,Integer> results = new HashMap<>();
for (String one : inp) {
String[] parts = one.split(" ");
String ts = parts[0];
int val = results.computeIfAbsent(ts, v-> 0);
results.put(ts, ++val);
}
System.out.println(results);
}
注意:还有其他方法可以处理地图递增。这只是一个例子。
样本输出:
{1112323=2, 9988778=1}
现在,如果将来可能想要执行其他操作,那么使用对象可能会很有趣。
所以一个类可能是:
private static class Entry
{
private final String ts;
private final String code;
private final String desc;
public Entry(String ts, String code, String desc)
{
// NOTE: error handling is needed
this.ts = ts;
this.code = code;
this.desc = desc;
}
public String getTs()
{
return ts;
}
public static Entry fromLine(String line)
{
Objects.requireNonNull(line, "Null line input");
// NOTE: other checks would be good
String[] parts = line.split(" ");
// NOTE: should verify the basic parts
return new Entry(parts[0], parts[1], parts[2]);
}
// other getter methods
}
然后可以做类似的事情:
List<Entry> entries = new ArrayList<>();
for (String one : inp) {
entries.add(Entry.fromLine(one));
}
Map<String,Integer> res2 = entries.stream()
.collect(Collectors.groupingBy(x->x.getTs(),
Collectors.summingInt(x -> 1)));
System.out.println(res2);
(目前相同的样本输出)。但是,如果需要扩展以计算 400 个代码的数量或其他什么,则更改流是微不足道的,因为对象具有数据。当然,这种方法还有更多的扩展。