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

狂风中的少年 提交于 2020-01-06 21:23:20

问题


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?


回答1:


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 Points should be compared by comparing their x values, which takes several lines of code, or you can use one of the built-in Comparators.

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));



回答2:


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.




回答3:


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?



来源:https://stackoverflow.com/questions/34971918/sorting-an-arraylist-based-on-a-class-data-members-data-member

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!