We have a ArrayList. It contains duplicate employee objects with only difference in their age, but name and id will be same. So while removing the duplicates, we have to keep the employee with maximum age and remove all other duplicates. This is one of the questions asked by an interviewer in one of the interviews.
I tried solving this. It is giving me correct result, but I am not sure with my approach as I am changing the state of the object in equals method. Is there any other approach to solve this problem?
Code Snippet below: -
package practice;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
class Employee {
private int id;
private String name;
private int age;
Employee(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public int hashCode() {
return (31*(name.hashCode()) + 31);
}
#Override
public boolean equals(Object obj) {
if ((obj instanceof Employee)) {
if (((Employee)obj).getId() == this.id && (((Employee)obj).getName().equalsIgnoreCase(this.name))) {
if(this.age > ((Employee)obj).getAge()) {
((Employee)obj).setAge(this.age);
}
return true;
} else
return false;
} else
return false;
}
}
public class ListDuplicateRemoval {
public static List<Employee> removeDuplicates(List<Employee> employees) {
Set<Employee> set = new HashSet<>();
for (int i = 0; i < employees.size(); i++) {
set.add(employees.get(i));
}
/*for (int i = 0; i < set.size(); i++) {
System.out.println(set.iterator().next().getAge());
}*/
employees.removeAll(employees);
employees.addAll(set);
return employees;
}
public static void main(String[] args) {
Employee e1 = new Employee(1, "Mike", 20);
Employee e2 = new Employee(1, "Mike", 21);
List <Employee> list = new ArrayList<>();
list.add(e1);
list.add(e2);
removeDuplicates(list);
System.out.println(list.size());
System.out.println(list.get(0).getAge());
}
}
No this solution is really awful. equals should never, ever, modify the state of the objects it's comparing.
Create a class containing the information that identifies employees uniquely, and which properly override equal() and hashCode(). Then use a Map containing these identication info as key, and the employee with the largest age as value. Then get the values and make it a list:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
class Employee {
private int id;
private String name;
private int age;
Employee(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
int getId() {
return id;
}
String getName() {
return name;
}
int getAge() {
return age;
}
#Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
class DuplicateRemoval {
public static void main(String[] args) {
List<Employee> employeeList = Arrays.asList(
new Employee(1, "Joe", 23),
new Employee(2, "Joe", 23),
new Employee(1, "Joe", 21),
new Employee(1, "Jane", 22),
new Employee(1, "Jane", 20)
);
Map<EmployeeKey, Employee> map = employeeList.stream().collect(
Collectors.toMap(e -> new EmployeeKey(e.getId(), e.getName()),
Function.identity(),
(e1, e2) -> e1.getAge() > e2.getAge() ? e1 : e2)
);
List<Employee> result = new ArrayList<>(map.values());
System.out.println("result = " + result);
}
private static class EmployeeKey {
private int id;
private String name;
EmployeeKey(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EmployeeKey that = (EmployeeKey) o;
return id == that.id &&
Objects.equals(name, that.name);
}
#Override
public int hashCode() {
return Objects.hash(id, name);
}
}
}
Implement a Comparator<Employee>
Have the compare method take into account age.
Have the equals method ignore age.
use equals to identify duplicates.
use compare to determine which duplicate to keep.
Related
I have 2 classes
Mother and Newborn
Class Mother:
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class Mother extends NewBorn {
private List<NewBorn> newBornList = new ArrayList<>();
private Set<NewBorn> children;
private int id;
private String name;
private int age;
public Mother(Mother mother, List<NewBorn> newBornList, Set<NewBorn> children, int id, String name, int age) {
super(mother);
this.newBornList = newBornList;
this.children = children;
this.id = id;
this.name = name;
this.age = age;
}
public Mother(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Mother(int id, String gender, String name, int birthdate, int weight, int height, List<NewBorn> newBornList, Set<NewBorn> children, int id1, String name1, int age) {
super(id, gender, name, birthdate, weight, height);
this.newBornList = newBornList;
this.children = children;
this.id = id1;
this.name = name1;
this.age = age;
}
public List<NewBorn> getNewBornList() {
return newBornList;
}
public void setNewBornList(List<NewBorn> newBornList) {
this.newBornList = newBornList;
}
public Set<NewBorn> getChildren() {
return children;
}
public void setChildren(Set<NewBorn> children) {
this.children = children;
}
#Override
public int getId() {
return id;
}
#Override
public void setId(int id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "Mother{" +
"newBornList=" + newBornList +
", children=" + children +
", id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
Class NewBorn:
public class NewBorn {
private Mother mother;
public NewBorn(Mother mother) {
this.mother = mother;
}
public NewBorn() {
}
public Mother getMother() {
return mother;
}
public void setMother(Mother mother) {
this.mother = mother;
}
private int id;
private String gender;
private String name;
private int birthdate;
private int weight;
private int height;
private int motherId;
public NewBorn(int id, String gender, String name, int birthdate, int weight, int height) {
this.id = id;
this.gender = gender;
this.name = name;
this.birthdate = birthdate;
this.weight = weight;
this.height = height;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBirthdate() {
return birthdate;
}
public void setBirthdate(int birthdate) {
this.birthdate = birthdate;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getMotherId() {
return motherId;
}
public void setMotherId(int motherId) {
this.motherId = motherId;
}
#Override
public String toString() {
return "NewBorn{" +
"mother=" + mother +
", id=" + id +
", gender='" + gender + '\'' +
", name='" + name + '\'' +
", birthdate=" + birthdate +
", weight=" + weight +
", height=" + height +
", motherId=" + motherId +
'}';
}
}
I have to get the mother older then 25years old that have child more then 4000g weigth
I did the following
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
List<Mother> motherabove = above25YoAndChildHeavierThen4000g(mothers, newBorns);
System.out.println("List with mothers above 25 years old and childs that are over 4000g weigth: " + motherabove + "\n");
}
public static List<Mother> parseMotherFileTxt() throws IOException {
List<Mother> mothers = new ArrayList<>();
BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\mamy.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] s = line.split("\\s");
mothers.add(new Mother(Integer.parseInt(s[0]), s[1], Integer.parseInt(s[2])));
}
bufferedReader.close();
return mothers;
}
public static List<NewBorn> parseNewBornFileTxt() throws IOException {
List<NewBorn> newBorn = new ArrayList<>();
BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\noworodki.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] s = line.split("\\s");
newBorn.add(new NewBorn(Integer.parseInt(s[0]), s[1], s[2], Integer.parseInt(s[4]), Integer.parseInt(s[5]), Integer.parseInt(s[6])));
}
bufferedReader.close();
return newBorn;
}
public static List<Mother> above25YoAndChildHeavierThen4000g(List<Mother> motherList, List<NewBorn> newBornList) {
return motherList.stream()
.filter(mother -> mother.getAge() > 25)//over 25yo
.filter(mother -> mother .getMotherId() == newBorn.getId())//get mother that have same id as child so assuming that means that this is the mother of the child
.filter(newBorn-> newBorn.getWeight() > 4000)//child over 4000g
.collect(Collectors.toList());// I expect to collect all the filters and return the correct output : Example Mother is : 112 Laura 38
and she have a child : 29 s Gabriel 1999-11-16 4100 54 112 = where 112 is the mother id that `I know is child of the mother`
}
I think something is wrong in the relation between the classes because I assume that the filter should work just fine if everything else is ok.
Normally should have mother has a list of children and a specific child has a field mother so with this I should be able to filter through.
I think you are looking for something like:
public static List<Mother> above25YoAndChildHeavierThen4000g(List<Mother> motherList, List<NewBorn> newBornList) {
return motherList.stream()
.filter(mother -> mother.getAge() > 25)
.filter(mother -> mother.getChildren().stream()
.anyMatch(child -> child.getWeight() > 4000))
.collect(Collectors.toList());
}
However the code overall definitely needs cleaning as advised in the comments
public List motherMoreThan() {
List list = new ArrayList<>();
for (Mother mother : mothers) {
if (mother.getAge() > 25 && isChildOver4000(mother)) {
list.add(mother);
}
}
return list;
}
public boolean isChildOver4000(Mother mother) {
for (Newborn newborn : mother.getList()) {
if (newborn.getWeight() > 4000) {
return true;
}
}
return false;
}
you can call them like this :
System.out.println("\nMothers over 25 Years old with childer heavier than 4000g;");
app.motherMoreThan()
.forEach(System.out::println);
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 1 year ago.
I have an array in the main class which holds Employee class objects. I'm trying to generate a unique ID for each object but it is printing the same ID for all the objects
Main class:
public static void main(String[] args) {
Employee employee1 = new Employee("Luke", 36);
Employee employee2 = new Employee("Martin", 49);
Employee employee3 = new Employee("Kevin", 21);
Employee employee4 = new Employee("Sam", 43);
Employee employee5 = new Employee("Nicole", 45);
Employee employee6 = new Employee("Linta", 21);
Employee[] allEmployees = { employee1, employee2, employee3, employee4, employee5, employee6 };
for (int i = 0; i < allEmployees.length; i++) {
System.out.println(allEmployees[i]);
}
}
Employee class
public class Employee {
private String name;
private int age;
private static String employeeID = "0";
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = getNextUniqueID();
}
public String getName() {
return name;
}
public String setName(String name) {
this.name =name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getNextUniqueID() {
int id = Integer.parseInt(employeeID);
++id;
return Integer.toString(id);
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
}
I want the employeeID as string and I can't use java.util.UUID; for my project.
You need a static variable associated with the class to maintain the unique id and an instance variable to keep that particular employee's ID in the class.
private String employeeID; // instance member
private static String uniqueID = "0"; // static class variable
public static String getNextUniqueID() {
int id = Integer.parseInt(uniqueID); // get the static variable
++id; // increment it
uniqueID = Integer.toString(id); // update the static variable
return uniqueID; // return the value to use for the employee
}
Then in the Employee constructor, use the static member:
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = Employee.getNextUniqueID();
}
updated Employee class:
public class Employee {
private String name;
private int age;
private String employeeID;
private static String uniqueID = "0";
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = Employee.getNextUniqueID();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getNextUniqueID() {
int id = Integer.parseInt(uniqueID);
++id;
uniqueID = Integer.toString(id);
return uniqueID;
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
}
Output:
Luke 36 1
Martin 49 2
Kevin 21 3
Sam 43 4
Nicole 45 5
Linta 21 6
You should store last generated id in static field but use non static for id of certain employee.
Also you should use AtomicInteger type for thread safety which you can convert to String. Check that:
import java.util.concurrent.atomic.AtomicInteger;
public class Employee {
private String employeeID;
private String name;
private int age;
private static AtomicInteger lastGeneratedId = new AtomicInteger(0);
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = getNextUniqueID();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getNextUniqueID() {
return String.valueOf(lastGeneratedId.incrementAndGet());
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
public static void main(String[] args) {
Employee employee1 = new Employee("Luke", 36);
Employee employee2 = new Employee("Martin", 49);
Employee employee3 = new Employee("Kevin", 21);
Employee employee4 = new Employee("Sam", 43);
Employee employee5 = new Employee("Nicole", 45);
Employee employee6 = new Employee("Linta", 21);
Employee[] allEmployees = { employee1, employee2, employee3, employee4, employee5, employee6 };
for (int i = 0; i < allEmployees.length; i++) {
System.out.println(allEmployees[i]);
}
}
}
I tried hard to make it. But I've got an error message
"Student is not abstract and does not override abstract method compareTo(Object) in Comparable
class Student extends Person {"
abstract class Person implements Comparable {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Student extends Person {
private int id;
public Student(String name, int id) {
super(name);
this.id = id;
}
public String toString() {
return Integer.toString(id);
}
public int getId() {
return this.id;
}
#Override
public int compareTo(Student s) {
if (this.id < s.getId()) {
return -1;
}else if (this.id > s.getId()) {
return 1;
}
return 0;
}
}
#Override
public int compareTo(Student s) {
if (this.id < s.getId()) {
return -1;
}else if (this.id > s.getId()) {
return 1;
}
return 0;
}
this is where I think having a problem...
As already explained by #Andreas, make Student implements Comparable, not Person.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
abstract class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
class Student extends Person implements Comparable<Student> {
private int id;
public Student(String name, int id) {
super(name);
this.id = id;
}
public String toString() {
return Integer.toString(id);
}
public int getId() {
return this.id;
}
#Override
public int compareTo(Student o) {
return Integer.compare(this.id, o.id);
}
}
Demo
public class Main {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("Abc", 321));
list.add(new Student("Xyz", 12));
list.add(new Student("Mnp", 123));
Collections.sort(list);
System.out.println(list);
}
}
Output:
[12, 123, 321]
I have a List and a Map as below:
public class student {
private String name;
private String age;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
student(String id,String name,String age)
{
}
}
List<student> stulist = Arrays.asList(new student("1", "vishwa",null),
new student("3", "Ravi",null),
new student("2", "Ram",null));
Map<String,String> newmap = new HashMap() {
{
put("1","20");
put("2","30");
}
};
I am comparing like this: If id in map matches the id in list then add
age from Map to age of List.
I have tried this so far , but i am not able to get it.
newmap.entrySet().stream().filter(entry->entry.getKey().equals(student::getId)).collect(..collect here to list..);
stulist = stulist.stream().map(instance -> {
student studentInstance = instance;
studentInstance.setAge(newMap.getOrDefault(studentInstance.getId(),"<default age>"));
return studentInstance;
}).collect(Collectors.toList()); ;
ps: Use proper naming conventions. Change the class name student to Student.
Here is solution, assuming I got the question right:
import java.util.*;
import java.util.stream.*;
public class Answer {
public static void main(String[] args) {
List<Student> studentsWithoutAge = Arrays.asList(
new Student("1", "Vishwa", null),
new Student("3", "Ravi", null),
new Student("2", "Ram", null)
);
Map<String,String> ageById = new HashMap() {{
put("1","20");
put("2","30");
}};
List<Student> studentsWithAge = addAge(studentsWithoutAge, ageById);
System.out.println("Students without age: " + studentsWithoutAge);
System.out.println("Students with age: " + studentsWithAge);
}
static List<Student> addAge(List<Student> students, Map<String,String> ageById) {
return students.stream()
.map(student -> {
String age = ageById.getOrDefault(student.getId(), null);
return new Student(student.getId(), student.getName(), age);
})
.collect(Collectors.toList());
}
}
class Student {
private String name;
private String age;
private String id;
Student(String id,String name,String age){
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return String.format("Student: id = %s, name = %s, age = %s", this.id, this.name, this.age);
}
}
Implement Student class as #Zgurskyi comment, and then use this on main:
stulist.forEach(stu -> {
stu.setAge(newmap.getOrDefault(stu.getId(), null));
});
Use Collectors.toList()
// Accumulate names into a List
List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());
If I have the following class:
public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values on attributes
}
// getters & setters
}
How can I use comparator that compares by name, then age, then id?
You need to implement it so that it orders by preferred elements. That is, you need to compare by name, then if that comparison is equal, compare by age, etc. An example is listed below:
public class EmployeeComparator implements Comparator<Employee> {
#Override
public int compare(Employee e1, Employee e2) {
int nameDiff = e1.getName().compareTo(e2.getName());
if(nameDiff != 0) {
return nameDiff;
}
int ageDiff = e1.getAge() - e2.getAge();
if(ageDiff != 0) {
return ageDiff;
}
int idDiff = e1.getEmpId() - e2.getEmpId();
return idDiff;
}
}
Update
Came across this a moment ago: How to compare objects by multiple fields One of the answers linked to ComparatorChain which will invoke multiple comparators in sequence until a non-zero result is received from a comparator or all comparators are invoked. This should probably be your preferred solution.
Perhaps this (untested) implementation of Comparator#compare() will do the trick.
int compare(Employee e, Employee f)
{
int val = e.name.compareTo(f.name);
if(val == 0)
{
val = e.age - f.age;
if(val == 0)
{
val = e.empId - f.empId;
}
}
return val;
}
You can also implement the Comparable Interface in your class.
for example, something like this:
public class Employee implements Comparable<Employee>{
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values on attributes
}
// getters & setters
public int compareTo(Employee o) {
int ret = this.name.compareTo(o.name);
if(ret == 0)
ret = this.age - o.age;
if(ret == 0)
ret = this.empId - o.empId;
return ret;
}
}
so you don't have to implement a extra class to compare your Employees.
Implement it
public class Employee {
private int empId;
private String name;
private int age;
/**
* #param empId
* #param name
* #param age
*/
public Employee(int empId, String name, int age) {
super();
this.empId = empId;
this.name = name;
this.age = age;
}
/**
*
*/
public Employee() {
super();
// TODO Auto-generated constructor stub
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//Compare by name, age and then id
public static Comparator<Employee> COMPARE_EMPLOYEE = new Comparator<Employee>() {
public int compare(Employee one, Employee other) {
//Compare Name
if (one.getName().compareToIgnoreCase(other.getName()) == 0) {
//Compare age
if((one.getAge() - other.getAge()) == 0) {
// Now check with id is useless
// So directly return result of compare by id
return one.getEmpId() - other.getEmpId();
} else { //If age Not equal
return one.getAge() - other.getAge();
}
} else { //If name not equal
return one.getName().compareToIgnoreCase(other.getName());
}
}
};
}
Use :
List<Employee> contacts = new ArrayList<Employee>();
//Fill it.
//Sort by address.
Collections.sort(contacts, Employee.COMPARE_EMPLOYEE);
Read Sorting an ArrayList of Contacts , this must help you and you will get more ideas and different different types of use of Comparator.
guava ComparisonChain:
List<Employee> list = new ArrayList<Employee>();
//...
Collections.sort(list, new Comparator<Employee>(){
#Override
public int compare(Employee e1, Employee e2) {
return ComparisonChain.start()
.compare(e1.empId, e2.empId)
.compare(e1.name, e2.name)
.compare(e1.age, e2.age).result();
}});
Use this:
public class Test
{
public static void main(String[] args)
{
Employee emp1 = new Employee(2, "Tom", 20);
Employee emp2 = new Employee(1, "Tom", 20);
Employee emp3 = new Employee(3, "Hank", 21);
List<Employee> list = new ArrayList<>();
list.add(emp1);
list.add(emp2);
list.add(emp3);
Collections.sort(list, new Employee().new MyComparator());
System.out.println(list);
}
}
class Employee
{
private int empId;
private String name;
private int age;
public Employee()
{}
public Employee(int empId, String name, int age)
{
this.empId = empId;
this.name = name;
this.age = age;
}
class MyComparator implements Comparator<Employee>
{
#Override
public int compare(Employee e1, Employee e2)
{
if(e1.name.compareTo(e2.name) == 0)
{
if(((Integer)e1.age).compareTo(e2.age) == 0)
{
return ((Integer)e1.empId).compareTo(e2.empId);
}
else
{
return ((Integer)e1.age).compareTo(e2.age);
}
}
return e1.name.compareTo(e2.name);
}
}
#Override
public String toString()
{
return "Employee [empId=" + empId + ", name=" + name + ", age=" + age + "]";
}
}
The Comparator interface defines two methods: compare() and equals().
The compare() method, compares two elements for order:
int compare(Object obj1, Object obj2)
obj1 and obj2 are the objects to be compared. This method returns zero if the objects are equal. It returns a positive value if obj1 is greater than obj2. Otherwise, a negative value is returned.
By overriding compare(), you can alter the way that objects are ordered. For example, to sort in a reverse order, you can create a comparator that reverses the outcome of a comparison.
The equals() method, tests whether an object equals the invoking comparator: boolean equals(Object obj)
obj is the object to be tested for equality. The method returns true if obj and the invoking object are both Comparator objects and use the same ordering. Otherwise, it returns false.
Example:
import java.util.*;
class Dog implements Comparator<Dog>, Comparable<Dog> {
private String name;
private int age;
Dog() {
}
Dog(String n, int a) {
name = n;
age = a;
}
public String getDogName() {
return name;
}
public int getDogAge() {
return age;
}
// Overriding the compareTo method
public int compareTo(Dog d) {
return (this.name).compareTo(d.name);
}
// Overriding the compare method to sort the age
public int compare(Dog d, Dog d1) {
return d.age - d1.age;
}
}
public class Example {
public static void main(String args[]) {
// Takes a list o Dog objects
List<Dog> list = new ArrayList<Dog>();
list.add(new Dog("Shaggy", 3));
list.add(new Dog("Lacy", 2));
list.add(new Dog("Roger", 10));
list.add(new Dog("Tommy", 4));
list.add(new Dog("Tammy", 1));
Collections.sort(list); // Sorts the array list
for(Dog a: list) // printing the sorted list of names
System.out.print(a.getDogName() + ", ");
// Sorts the array list using comparator
Collections.sort(list, new Dog());
System.out.println(" ");
for(Dog a: list) // printing the sorted list of ages
System.out.print(a.getDogName() +" : "+ a.getDogAge() + ", ");
}
}
Check it out for more Java Comparator examples.