简体   繁体   中英

Sorting an ArrayList based on a class data member's data member

So, I have a class which contains another class object as its data member. I have created an ArrayList based on this prototype. Here is the code:

    package Stack;

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


    class Point
   {
       int x;
       int y;

       Point(int x, int y)
       {
           this.x = x;
           this.y = y;
       }
   }

   public class MergeInterval
   {

       Point P;

       MergeInterval() {}


       public static void main(String args[])
       {
           ArrayList<Point> arr = new ArrayList<Point>();
          // Point p = new Point(6,8);

           arr.add(new Point(6,8));
           arr.add(new Point(1,9));
           arr.add(new Point(2,4));
           arr.add(new Point(4,7));

        //   System.out.println(arr.get(1).x + " " + arr.get(1).y);

       }
   }

I need to sort this Arraylist as to get the output as following: {1,9} {2,4} {4,7} {6,8}

Basically I needed to sort this structure based on the 'x' variable of Class 'Point' but using the inbuilt 'sort' method. How do I achieve it?

The List.sort(...) method takes a Comparator which determines how the elements in the list should be compared to each other for the purposes of determining the order. You can either implement Comparator yourself to specify that the Point s should be compared by comparing their x values, which takes several lines of code, or you can use one of the built-in Comparator s.

The Comparator interface defines default implementations for the case where you want to compare via something that is a simple function of the list element.

Since you are comparing on an int property, you can use Comparator.comparingInt as follows:

arr.sort(Comparator.comparingInt(p -> p.x));

One way to do this would be if your Point class implements Comparable. Processes like sorting require some kind of comparisons to happen. Please take a look at this link .

In this case, your Point class would implement Comparable. For this to work, your Point class would also require a compareTo(Point other) method. In your case, this function would return 0 if this.x == other.x, -1 if this.x < other.x and 1 otherwise.

Does that answer your question?

Create a comparator like this:

Comparator<Point> comparator = new Comparator<Point>() {

    @Override
    public int compare(Point o1, Point o2) {
        return Integer.compare(o1.x, o2.x);
    }
};

arr.sort(comparator);

You can add this code after you have populated the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM