如何使用 lambda 解析字符串列表并向 map<string,integer> 添加值



在我的控制台项目中,我在一行上接收输入{String resource}{int quantity}(可以接收多对,例如:3 Motes 5 stones 5 Shards

我的目标是重构while循环的主体,以使用尽可能多的lambda。我很想减少if-else语句的数量,并使用谓词,但我是一个新手,我更喜欢寻找指针,我还可以尝试什么。

我已经查看了Collectors,Arrays.stream((的javadoc,还阅读了Oracle JDK 8 lambdas和函数式编程中的教程,但显然需要更多的实用示例。

目标是为其中一个legendaries Map键获取250的资源并停止程序。我用Scanner解析值,用一个空格分隔,并实现我的逻辑如下:

private final static int REQUIRED_QUANTITY = 250;
private static boolean gameOver = false;
Map<String, String> legendary = new HashMap<>();
legendary.put("shards", "Shadowmourne");
legendary.put("fragments", "Valanyr");
legendary.put("motes", "Dragonwrath");
Map<String, Integer> resources = new HashMap<>();
while (true) {
String[] loot = scanner.nextLine().toLowerCase().split(" ");
String material = null;
int quantity = 0;
for (int i = 0; i < loot.length; i++) {
if (i % 2 != 0) {
material = loot[i];
} else {
quantity = Integer.parseInt(loot[i]);
}
if (material != null && quantity != 0) {
if (resources.containsKey(material.toLowerCase())) {
resources.replace(material, resources.get(material) + quantity);
}
resources.putIfAbsent(material.toLowerCase(), quantity);
material = null;
quantity = 0;
}
}
resources.forEach((s, integer) -> {
if (integer > REQUIRED_QUANTITY) {
System.out.println("Legendary obtained: " + legendary.get(s));
gameOver = true;
}
});

我做了一些更改。

  • 只对2个值使用for循环。一次只处理一行
  • 使用compute处理地图更新
  • 放入占位符以检查是否有适当的资源(输入时可能拼写错误
private final static int REQUIRED_QUANTITY = 250;
private static boolean gameOver = false;
Map<String, String> legendary = new HashMap<>();
legendary.put("shards", "Shadowmourne");
legendary.put("fragments", "Valanyr");
legendary.put("motes", "Dragonwrath");

Map<String, Integer> resources = new HashMap<>();
Scanner scanner = new Scanner(System.in);
while (!gameOver) {
String[] loot =
scanner.nextLine().toLowerCase().split("\s+");
for (int i = 0; i < loot.length; i+=2) {
String material = loot[i+1];
if (!legendary.containsKey(material)) {
// do some error processing
}
int quantity = Integer.parseInt(loot[i]);   
// you may want to catch exception here.
resources.compute(material.toLowerCase(),
(k, v) -> v == null ? quantity : v + quantity);

}
resources.forEach((s, integer) -> {
if (integer > REQUIRED_QUANTITY) {
System.out.println("Legendary obtained: "
+ legendary.get(s));
gameOver = true;
}
});
}

我已经将您提供的代码封装到一个类中。

映射resources已重命名并更改为实例变量Map<String, Integer> resourceToQuantity。标志gameOver也被制成一个实例变量。

主要的游戏逻辑位于collectResources()方法中,主要的增强功能在这里进行:

  • 标志gameOver被用作while loop的退出条件
  • nested for loop的条件发生了改变
  • for loop被缩短,if/else语句被删除
  • 变量CCD_ 11和CCD_
  • 在循环的每次迭代中,CCD_ 13被合并并且总和被对照CCD_
  • 如果这个条件是肉标志gameOver被设置为true并且游戏循环退出
  • 正在打印收集的资源
public class LootHunter {
private final static int REQUIRED_QUANTITY = 250;
private static final Map<String, String> legendary = Map.of(
"shards", "Shadowmourne",
"fragments", "Valanyr",
"motes", "Dragonwrath"
);
private final Map<String, Integer> resourceToQuantity;
private boolean gameOver;
public LootHunter() {
this.resourceToQuantity = new HashMap<>();
}
public void collectResources() {
while (!gameOver) {
Scanner scanner = new Scanner(System.in);
String[] loot = scanner.nextLine().toLowerCase().split(" ");
for (int i = 0; i < loot.length - 1; i += 2) {
int quantity = Integer.parseInt(loot[i]);
String material = loot[i + 1];
int totalQuantity = resourceToQuantity.merge(material, quantity, Integer::sum); // merges quantities and returns the sum
if (totalQuantity > REQUIRED_QUANTITY) {
System.out.printf("You win! %d of %s have been collected.%n", totalQuantity, material);
System.out.println("Legendary item obtained: " + legendary.get(material));
gameOver = true;
break;
}
}
}
printAllResources(); // prints all the collected resources
}
public void printAllResources() {
System.out.println("List of resources collected:");
resourceToQuantity.forEach((material, quantity) ->
System.out.printf("%s: %d%n", material, quantity));
}
public static void main(String[] args) {
LootHunter lootHunter = new LootHunter();
lootHunter.collectResources();
}
}

输入:

"30 shards 10 fragments 50 motes 80 fragments 70 shards 180 fragments"

输出

You win! 270 of fragments have been collected.
Legendary item obtained: Valanyr
List of resources collected:
shards: 100
motes: 50
fragments: 270

相关内容

最新更新