0

Please Help me with this code below

I am getting an output like this

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

I not able to resolve the issue of name output it is printing 'Chaya' instead of 'Bhanu'. Can I use a toString method to print the phone number values
Please Elaborate.....

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());        
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself. Questions without a clear problem statement are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Lino Jul 03 '18 at 14:22
  • Possible duplicate of [How do I print out all keys in hashmap?](https://stackoverflow.com/questions/26847081/how-do-i-print-out-all-keys-in-hashmap) which is a duplicate of [Printing HashMap In Java](https://stackoverflow.com/questions/5920135/printing-hashmap-in-java) – LuCio Jul 03 '18 at 14:37

1 Answers1

3

You can use :

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"));
}

Note :

  • Your method name should be significant name (Instead change it to getName)
  • I assume that your method should return a String(name of user who have this phone number) and not a list of Long
  • What if your method not find any result? (You can throw an exception)
  • The code would be more readable if the phno value would be passed as a second argument to the method (thank you Conffusion), then call your method like this getName(map, phno)
  • The design you are using is not good at all, instead I would suggest to create a class of users which hold username, and a List of phone numbers, It will be easy to read and to manipulate.
  • Name of variables should be in lower case not upper case

Of If you want to get all the name of users which have that phone number you can use :

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());
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • 1
    The code would be more readable if the phno value would be passed as a second argument to the method. (+1 for the use of Optional :) – Conffusion Jul 03 '18 at 14:34
  • 1
    Instead of `if (result.isPresent()) { ... } else { throw ... }` in the first code sample you can continue method chaining: `findFirst().map(entry -> entry.getKey())..orElseThrow(() -> new Exception("No result found"));` – LuCio Jul 03 '18 at 14:44
  • @LuCio I'm using `result.get().getKey();` not just `result.get();` In this case how you can continue chaining? – Youcef LAIDANI Jul 03 '18 at 14:46
  • @LuCio yes this is correct I forgot the `map(..)` thank you I changed my code – Youcef LAIDANI Jul 03 '18 at 14:49