项目的限制要求我使用 aHashMap作为我的数据源。我被要求使用以下方法
getAccountsWithMinimum- 返回至少具有指定余额List的Accounts
问题是 HashMap 没有索引。所以我不能使用 For 循环来完成它。
我尝试改编我在 Stack Overflow 和 GeeksForGeeks 上发现的类似问题的代码。这种方法不仅没有奏效,而且对我也没有多大好处,因为我不明白为什么它有效,即使它有效(它没有)。
我尝试从我在 GeeksForGeeks 上找到的代码中使用它。它什么也不打印。
public void getAccountsWithMinumum() {
Iterator entries = accounts.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
Integer key = (Integer) entry.getKey();
Integer value = (Integer) entry.getValue();
System.out.println("Key = " + key + ", Value = " + value);
}
}
Run Code Online (Sandbox Code Playgroud)
帐户中的对象包含 (String)firstName、(String)lastName、(double)balance、(String)accountType 和 (String)AccountID 属性。
我想得到的是返回所需列表并将其打印到控制台的东西,以便我可以确认它。
我不需要有人为我做这件事,因为我怀疑这是我最后一次被要求做这件事或类似的事情。要么是一些非常沉重的手握提示,所以我可以填补空白,或者如果它更容易做到这一点,那么详细解释我为什么这样做将不胜感激。
使用 Java 8 流:
List<Accout> accounts = accounts.values().stream()
.filter(account -> account.getBalance() > threshold)
.collect(Collectors.toList())
Run Code Online (Sandbox Code Playgroud)
与foreach:
List<Account> accountsWithMinimum = new ArrayList<>();
for (Account acccount : accounts.values() ) {
if (account.balance > threshold) {
accountsWithMinimum.add(account);
}
}
Run Code Online (Sandbox Code Playgroud)
该接口的values方法Map返回Collection存储在地图中的值。也可以用来entrySet获取键值对的集合,或者keySet只获取键。
| 归档时间: |
|
| 查看次数: |
561 次 |
| 最近记录: |