基于排序类的数据成员的数据成员的ArrayList [英] Sorting an ArrayList based on a class data member's data member

查看:155
本文介绍了基于排序类的数据成员的数据成员的ArrayList的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有一个包含其他类对象作为其数据成员的类。我创建了基于该原型的ArrayList。这里是code:

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

       }
   }

我需要排序此ArrayList才能得到输出如下:
{1,9} {2,4} {4,7} {6,8}

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

基本上,我需要进行排序基于阶级点,但使用内置的排序方法的变量x这样的结构。我该如何实现呢?

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?

推荐答案

List.sort(...)方法需要的 比较 决定如何列表中的元素应互相比较以确定该命令的目的。您可以实施比较亲自指定通过比较在取值应该比较它们的 X 的价值观,这需要code的几行,或者您可以使用内置的比较取值之一。

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.

由于您是在 INT 属性比较,你可以使用<一个href=\"http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#comparingInt-java.util.function.ToIntFunction-\"相对=nofollow> Comparator.comparingInt 如下:

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

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

这篇关于基于排序类的数据成员的数据成员的ArrayList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆