请在下面提供此代码,以帮助我
我得到这样的输出
Enter name:Chaya
[455-567-8888, 655-884-4557, 811-115-5556]
Enter phone: 7666644556
7666644556 = [Chaya]
I need to get an output like this
Enter name: Chaya
455-567-8888
655-884-4557
811-115-5556
Enter phone: 7666644556
7666644556 = Bhanu
我无法解决名称输出的问题,因为它输出的是“ Chaya”而不是“ Bhanu”。我可以使用toString方法来打印电话号码值吗?
请详细.....
public class PhNo
{
private static String name;
private static long phno;
public static void main(String[] args)
{
HashMap<String, List<Long>> map = new HashMap<String, List<Long>>();
List<Long> One = new ArrayList<Long>();
One.add(1111111111L);
One.add(9444445555L);
List<Long> Two = new ArrayList<Long>();
Two.add(7666644556L);
List<Long> Three = new ArrayList<Long>();
Three.add(4555678888L);
Three.add(6558844557L);
Three.add(8111155556L);
List<Long> Four = new ArrayList<Long>();
Four.add(4555678899L);
Four.add(6558844566L);
Four.add(8666655556L);
map.put("Arya", One);
map.put("Bhanu", Two);
map.put("Chaya", Three);
map.put("Dhamu", Four);
System.out.println("Enter name: ");
Scanner userInput = new Scanner(System.in);
name = userInput.nextLine();
List<Long> phoneNum = map.get(name);
System.out.println(String.valueOf(phoneNum).replaceAll("(\\d{3})(\\d{3})(\\d+)", "$1-$2-$3"));
System.out.println("Enter phone: ");
phno = userInput.nextLong();
System.out.println(phno+" = "+ getKeysByValue(map));
}
static List<String> getKeysByValue(Map<String, List<Long>> map)
{
return map.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getKey(), name))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
}
答案 0 :(得分:3)
您可以使用:
static String getName(Map<String, List<Long>> users, Long phone) throws Exception {
return users.entrySet()
.stream()
.filter(entry -> entry.getValue().contains(phone))
.findFirst()
.map(user -> user.getKey())
.orElseThrow(() -> new Exception("No result found"));
}
注意:
getName
)getName(map, phno)
Of如果您想获得拥有该电话号码的所有用户名,则可以使用:
static List<String> getNameOfUsersByPhoneNumber(Map<String, List<Long>> map, Long phone) {
return map.entrySet()
.stream()
.filter(entry -> entry.getValue().contains(phone))
.map(entry->entry.getKey())
.collect(Collectors.toList());
}