Start course
Overview
Difficulty
Beginner
Duration
2h 16m
Students
26
Description

In this course, we'll learn the Collection framework and the Map Interface.

Learning Objectives

  • Collection Framework vs Array
  • Hierarchy of Collection Framework
  • List interface - ArrayList Class
  • Iterator Interface
  • Set Interface
  • Queue and Dequeue Interfaces
  • Map Interface

Intended Audience

  • Anyone looking to get Oracle Java Certification
  • Those who want to learn the Java Programming language from scratch
  • Java developers who want to increase their knowledge
  • Beginners with no previous coding experience in Java programming
  • Those who want to learn tips and tricks in Oracle Certified Associate – Java SE 8 Programmer certification exams

Prerequisites

  • No prior knowledge is required about the Java programming language
  • Basic computer knowledge
Transcript

Hi there. In our previous lesson, we used the sort() method of the Collections class to sort the elements in our list from smallest to largest or alphabetically. In this lesson, we'll talk about the comparator interface, which allows us to sort lists from largest to smallest or to sort them differently. If you're ready, let's move on to the Eclipse and get some practice. First, I will create a new class. I right click on the collectionsexample package and select the 'New', 'Class' option. The class name can be ComparatorExample. I'll check the checkbox for the main() method and click the 'Finish' button. First, I will create an ArrayList. List < Integer > <Integer> numsList = new ArrayList< >(); Now, I will add some elements to this list. numsList.add(10); I will copy and paste it below five times. The second element can be 5. The third element can be 13. The fourth element can be 7. The fifth element can be 20. The sixth element can be 2. Okay. I will now call the Collections.sort() method. As you can see, there are two types of the sort() method. We have already used the first method.

Now, let's look at the other method. If you notice, the first parameter of this method is a list. Here, we can write the name of our list again. So, I write numsList. The second parameter is the comparator. Now, let's create the parameter. First, I will define a new class which is outside the scope of this class. class MyNumbers. This class will implement the comparator interface. implements Comparator. Also, it's type of the integer because the data we want to compare is integer. Yes. If you notice, we are getting a compilation error because there is a method that we should override. I position the mouse over the MyNumbers class and select the 'Add unimplemented methods' option from the quick fix dialog that opens. So, the compare() method is overridden. Notice that this method has two parameters of type integer. Of course, the reason why this is integer is that we specify the Integer class as a type here. compare() method compares two numbers and returns a positive value if the first number o1 is greater than the second number o2.

This means, ordering the elements from smallest to largest. If less than, it returns a negative value. This means, ordering them from largest to smallest. Therefore, we'll create an if-else statement here. if(o1 > o2) { return 1; }  else if (o1 < o2) { return -1; } else { return 0; } Okay. This class is ready now. Let's call this class inside the sort() method. As the second parameter, I write new MyNumbers(). Now, we can print the elements on the console. System.out.println(numsList);. Now, the elements will sort ascending. Let's run the code and see. As you can see, it sorted as ascending. Now, let's order from largest to smallest. If we change the condition in the if-else statement we created in the compare() method, that is, if the first condition is o1 < o2, and the second condition is o1 > o2, then there will be an order from largest to smallest. Let's run it and test it. As you can see, this time, the numbers are sorted from largest to smallest. Yes. We can use the compare interface this way for ascending and descending sorts.

In addition, the compare interface offers the possibility to sort by different data. For example, you want to sort personal information such as name, age, and salary about your workplace by age or salary. You can still use the compare interface for this job. If you want, let's make a small example about this and end the lesson. Let's create a new package for this. I right click on the 'src' folder in the Collections project and select 'New', 'Class' options. Let the package name be comparatorapp. The class name can be Employees. I create the Employees class by clicking the 'Finish' button. In this class, I will create three variables that represent the person's name, age, and salary. String name; int age, salary; Now, let's create the constructor of this class. We can create this easily. I right click on the empty space with the mouse. I choose the 'Source' and 'Generate Constructor using Fields' options. I select all three variables from this window that opens and I click the 'Generate' button. As you can see, we have created the constructor.

Now, let's create the getter methods. Yes. So, this class of ours is ready. Now, let's create our test class. I right click on the comparatorapp package and select 'New', 'Class' options. The class name can be the ComparatorTest, and I will click the checkbox for the main() method and click the 'Finish' button. Now, let's create a new ArrayList that holds the information of the employees. List. The type of this list will be Employees because in this list, we will store the information of the employees, i.e., object of the Employees class. The name of this list can be employeeList. After the equal sign I write, new ArrayList< >(). Now, let's add some employees to this list. employeeList.add(new Employees()); Now, I will need to write the constructor parameters. The name can be "David", age can be 30, salary can be 1000. And, I will copy this line and paste it below five times. The name of the second employee can be "Alex", age, can be 25, salary can be 5000. The name of the third employee can be "Ronaldo", age can be 20, salary can be 2000.

The name of the fourth employee can be "Mary", age can be 35, salary can be 7000. The name of the second employee can be "Clark", age can be 27, salary can be 10000. The name of the last employee can be "James", age can be 23, salary can be 3000. Now, I will create a reference from the comparator interface. The type will be Employees. Name of the reference can be comparator. After the equal sign, I'll write Comparator.comparing(). The comparing() method is the static method of the comparator interface, so we can access it directly. And, we'll write in the parentheses according to which data we want to sort. For example, let's sort by age first. I write Employees :: getAge in parentheses. In the next line, I'm going to call the sort() method of the Collections class again. Collections.sort(); The first parameter will be the employeeList and the second parameter will be the comparator object. And lastly, let's print the information of the employees on the console using the for-each loop. for (Employees employee : employeeList).

In the loop I write, System.out.println("Name: " + employee.getName(). After the plus sign, double quotes again. "Age: " + employee.getAge(). And last,  "Salary: " + employee.getSalary());  Also, before the age and salary I put the \t. This is another escape character in Java. It leaves a tab of space so the output will look neater on the console screen. Yes. Everything is ready. Let's run the code and see. As you can see, the information is ordered according to age. Now, let's order them according to the salary. For this, I will change the getAge parameter with the getSalary parameter. Let's run it again. And this time, the information is sorted according to the salaries. The comparator interface in Java is like this. Let's take a short-break here. See you in the next lesson.

 

About the Author
Students
409
Courses
35
Learning Paths
2

OAK Academy is made up of tech experts who have been in the sector for years and years and are deeply rooted in the tech world. They specialize in critical areas like cybersecurity, coding, IT, game development, app monetization, and mobile development.

Covered Topics