尝试将以下用于将姓名和电话号码添加到 HashMap 的正常代码转换为 Java 8 中的 Lambda 表达式,并搜索给定姓名的电话号码。此代码在电子商务应用程序的模块中使用,用于搜索特定企业(公司)的电话号码
代码片段:
public static void main(String[] args){
Map<String, Integer> phonebook = new HashMap<>();
Scanner sc = new Scanner(System.in);
int cases = sc.nextInt();
sc.nextLine();
for (int i = 0;i < cases; i++){
String name = sc.nextLine();
int phoneNumber = sc.nextInt();
sc.nextLine();
phonebook.put(name, phoneNumber);
}
while (sc.hasNext()){
String query = sc.nextLine();
if (phonebook.containsKey(query)){
System.out.println(query + "=" + phonebook.get(query));
}else {
System.out.println("Not found");
}
}
sc.close();
}
看起来很基本,但无法解决。您能帮忙提供解决方案吗?
需要将上述代码转换为Lambda Java代码。
如果你想用 Lamba 表达式替换传统的循环语法。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
public class Phonebook {
public static void main(String[] args) throws IOException {
Map<String, Integer> phonebook = new HashMap<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int cases = Integer.parseInt(br.readLine());
IntStream.range(0, cases).forEach(i -> {
try {
String[] input = br.readLine().split(" ");
String name = input[0];
int phoneNumber = Integer.parseInt(input[1]);
phonebook.put(name, phoneNumber);
} catch (IOException e) {
e.printStackTrace();
}
});
String query;
while ((query = br.readLine()) != null) {
if (phonebook.containsKey(query)) {
System.out.println(query + "=" + phonebook.get(query));
} else {
System.out.println("Not found");
}
}
br.close();
}
}