java map 平均值_java - LinkedHashMap中以日期为键设置的平均值,按星期几 - 堆栈内存溢出...

使用流

您可以使用Java 8流非常快地完成此操作,但是作为一个衬套使用时,此特定用法可能会变得有些复杂,因此您可能需要对其进行拆分。

Calendar instance = Calendar.getInstance();

Map weekInAYearToAverage =

hourlyPrices

.entrySet()

.stream()

// Group all entries, where key is "MonthXDayName" and value is a list of entries

// This will give us Map>>

.collect(Collectors.groupingBy(dateDoubleEntry -> {

instance.setTime(dateDoubleEntry.getKey());

// Create String key as "MonthXDayName"

return "Month" + instance.get(Calendar.MONTH) +

DayOfWeek.of(instance.get(Calendar.DAY_OF_WEEK))

.getDisplayName(TextStyle.FULL, Locale.ENGLISH);

}))

// This would be a good place to split this line

.entrySet()

.stream()

// Map all groups, so we will have map where key is "MonthXDayName" and value is an average value or 0, if no values

.collect(Collectors.toMap(Map.Entry::getKey,

e -> e.getValue()

.stream()

.mapToDouble(Map.Entry::getValue)

.average()

.orElse(0)));

没有流

对于Java 6和7,在将流引入Java之前,请使用常规循环。

Calendar instance = Calendar.getInstance();

// Group entries by "MonthXDayName"

Map>> groupedEntries = new HashMap>>();

for (Map.Entry entry : hourlyPrices.entrySet()) {

instance.setTime(entry.getKey());

String key = "Month" + instance.get(Calendar.MONTH) +

DayOfWeek.of(instance.get(Calendar.DAY_OF_WEEK))

.getDisplayName(TextStyle.FULL, Locale.ENGLISH);

if (!groupedEntries.containsKey(key)) {

// If there will be a lot of entries, you might consider using LinkedList, as it's faster when adding big number of entries

groupedEntries.put(key, new ArrayList>());

}

groupedEntries.get(key).add(entry);

}

// Calculate average for every group

Map weekInAYearToAverage = new HashMap();

for (Map.Entry>> entry : groupedEntries.entrySet()) {

String key = entry.getKey();

double avg = 0;

if (entry.getValue().size() > 0) {

for (Map.Entry hourlyEntry : entry.getValue()) {

avg += hourlyEntry.getValue();

}

avg /= entry.getValue().size();

}

weekInAYearToAverage.put(key, avg);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值