Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display only names from objects stored in a list Java

I guess it is very simple question, but I am learing Java since few days and cannot resolve this:

in class Player: String getName() { return name; }

public class Main {
    public static void main(String[] args) {
        List<Player> footballTeam = new ArrayList<>();
        Player player1 = new Player(59, "John", 20); 
        Player player2 = new Player(67, "Roger", 22); 
        Player player3 = new Player(45, "Steven", 24);

        footballTeam.add(player1);
        footballTeam.add(player2);
        footballTeam.add(player3);

        System.out.println("Before Sorting : " + footballTeam);
        Collections.sort(footballTeam);
        System.out.println("After Sorting : " + footballTeam);
    }
}

How can I display the data after sorting but only the names, without ranking and age? This displays 3xSteven:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    for (int i = 0; i < footballTeam.size(); i++) {
        System.out.println(Player.getName());

>Solution :

You probably have a getter inside the Player class called getName() or something like that. I recommend you to inspect the Player class and start by understand it.

foreach(Player player : footballTeam)
    System.out.println(player.getName());

or

for (int i = 0; i < footballTeam.size(); i++)
    System.out.println(footballTeam.get(i).getName());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading