Good day. The program should produce a key and several values ​​for this key, but the values ​​are output in the form of a code: [{Person @ 1b6d3586 = [Phone @ 4554617c, Phone @ 74a14482]}] How to display in a standard form?

public class Task2 { public static void main(String[] args) { Map<Person, List<Phone>> personPhone = new HashMap<Person, List<Phone>>(); personPhone.put(new Person("Иван", "Иванов"), Arrays.asList(new Phone(88002000500L), new Phone(88002000500L))); System.out.println(Arrays.asList(personPhone)); } } class Phone { public long numberPhone; public Phone(long numberPhone) { this.numberPhone = numberPhone; } } class Person { public String name; public String lastName; public Person(String name, String lastName) { this.name = name; this.lastName = lastName; } } 
  • one
    you have not overridden the toString method (as well as hasdCode and equals) - Vartlok

2 answers 2

Add a toString() method to the Person and Phone classes

Person:

 @Override public String toString() { return "Person [name=" + name + ", lastName=" + lastName + "]"; } 

Phone:

 @Override public String toString() { return "Phone [numberPhone=" + numberPhone + "]"; } 

Or process the Map with a loop:

 for (Entry<Person, List<Phone>> entry : personPhone.entrySet()) { Person person = entry.getKey(); List<Phone> phones = entry.getValue(); ... Распечатываем удобным способом } 

    Try this:

     personPhone.entrySet().forEach( entry -> entry.getValue().forEach( phone -> { Person person = entry.getKey(); System.out.println(person.name + " " + person.lastName + " " + phone.numberPhone); } ) );