题解 | #配置文件恢复#
配置文件恢复
https://www.nowcoder.com/practice/ca6ac6ef9538419abf6f883f7d6f6ee5
使用stream过滤map
import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.stream.Collectors; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { static Map<String, String> map = new HashMap<String, String>() {{ put("reset", "reset what"); put("reset board", "board fault"); put("board add", "where to add"); put("board delete", "no board at all"); put("reboot backplane", "impossible"); put("backplane abort", "install first"); }}; public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextLine()) { // 注意 while 处理多个 case System.out.println(cmd(in.nextLine())); } } private static String cmd(String str) { String[] words = str.split(" "); List<Map.Entry<String, String>> list = map.entrySet().stream().filter(entry -> { String[] keywords = entry.getKey().split(" "); if (words.length != keywords.length) { return false; } for (int i = 0; i < keywords.length; i++) { if (!keywords[i].startsWith(words[i])) { return false; } } return true; }).collect(Collectors.toList()); return list.size() == 1 ? list.get(0).getValue() : "unknown command"; } }