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!

1
  • Your question was answered here already. Commented Apr 14, 2015 at 21:15

2 Answers 2

1

Implements a Comparator and then calls

Collections.sort(addressBook, yourComparator); 
Sign up to request clarification or add additional context in comments.

Comments

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++; } ... }

2 Comments

Where would this go and how would it look like in my code?
where you had the Collections.sort method before. I added it to your snippet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.