0

Hello i have problem i cant solve. I want to Sort list of Obj in java by value, String in this example. I khow to do this in C# but I can't in Java. I try "collection.sort" and "compareTo" but I did something wrong.

missing code is in Case 3

 public static void main(String[] args)
    {
        ArrayList<Animal> animals = new ArrayList<Animal>(); // deklaracja listy obiektów

        boolean exit = false; // zapętlenie menu
        while (!exit)
        {


            System.out.println("**MENU**\nWcisnij: \n1.Dodaj zwierze.\n2.Pokarz liste zwierzat. \n3.Posortuj liste po wieku\n4.Exit ");
            int menu = Integer.parseInt(new Scanner(System.in).nextLine());

            switch (menu)
            {
                case 1:

                        System.out.println("**POD MENU**\nWcisnij: \n1.Ssak \n2.Gad \n3.Ptak\n");
                        int subMenu = Integer.parseInt(new Scanner(System.in).nextLine()); // pod menu
                        {
                        if (subMenu == 1) // tworzenie obiektu ssak
                        {
                            Mammal mammal = new Mammal();
                            mammal.CreateMammal();
                            animals.add(mammal);
                        }
                ***

                case 3:
                // compare and sort objects in list by name and print ??
                // in C# i do sth like this but i dont know hot to bite this in java
                /*
                    var orderedAnimals = animals.OrderBy(x -> x.name); // algorytm sortowania
                                        for (var animal : orderedAnimals)
                                        {
                                            System.out.println(animal.toString());
                                        }

                */

2 Answers2

2

You can use Comparator Facility in Java for this.

Create a sub class like this

class SortByName implements Comparator<Animals> { 
    // Used for sorting in ascending order of  name 
    public int compare(Animals a, Animals b) { 
        return a.name.compareTo(b.name); 
    } 
}

In Main Class Invoke sub class by

Collections.sort(animals, new SortByName());
shihabudheenk
  • 593
  • 5
  • 18
0

I'm assuming you want to alphabetically order the names. Try this:

Add this import import java.util.Collections;

And then try this to loop through an ordered list:

ArrayList<Animals> byName = Collections.sort(animals);
IntStream.range(0, byName.size()).forEach(m -> System.out.println(byName.toString());
arcanium0611
  • 123
  • 12