0

I wanted to know how I can order the linkedlist addressBook in order of the integer/age from youngest to oldest. I am aware that Collections.sort(addressBook); would organize the list alphabetically, but I do not intend to actually need it in my end product.

import java.io.*;
import java.util.*;

public class ABook
{
   public static void main (String args[])
   {
       LinkedList addressBook = new LinkedList(); 
       Scanner input = new Scanner(System.in);
       int n = 0; 
       do{
       System.out.println("Would you like to add a friend? (Say Y or N)"); 
       String reply = input.nextLine();
       if(reply.equals("Y"))
       {
        System.out.println("What is the name of your friend?");
        String name = input.nextLine();
        System.out.println("What is the age of your friend?");
        int age = input.nextInt();
        Friend newFriend = new Friend(name,age);
        addressBook.add("Name: " + newFriend.name + "; " + "Age: " + newFriend.age);
        Collections.sort(addressBook);
        System.out.println("This is your Address Book so far: " + addressBook);
        n++;
    }     
      ...
}

If anyone could let me know, that would be great.

Thank you!

Aman
  • 41
  • 7
  • Your question was answered [here](http://stackoverflow.com/questions/2477261/how-to-sort-a-collectiont) already. – Turing85 Apr 14 '15 at 21:15

2 Answers2

1

Use a comparator.

import java.io.*;
import java.util.*;

public class ABook
{
   public static void main (String args[])
   {
       LinkedList addressBook = new LinkedList(); 
      

       Scanner input = new Scanner(System.in);
       int n = 0; 
       do{
       System.out.println("Would you like to add a friend? (Say Y or N)"); 
       String reply = input.nextLine();
       if(reply.equals("Y"))
       {
        System.out.println("What is the name of your friend?");
        String name = input.nextLine();
        System.out.println("What is the age of your friend?");
        int age = input.nextInt();
        Friend newFriend = new Friend(name,age);
        addressBook.add("Name: " + newFriend.name + "; " + "Age: " + newFriend.age);
         Comparator<CustomObject> comparator = new Comparator<CustomObject>() {
           public int compare(CustomObject c1, CustomObject c2) {
               return c2.getAge() - c1.getAge(); // use your logic
              }


       Collections.sort(addressBook,comparator);
        System.out.println("This is your Address Book so far: " + addressBook);
        n++;
    }     
      ...
}
Eddie Martinez
  • 13,582
  • 13
  • 81
  • 106
1

Implements a Comparator and then calls

Collections.sort(addressBook, yourComparator);
Ga Ye
  • 65
  • 1
  • 7