java list对象排序函数

java list对象排序函数


2024年6月19日发(作者:)

java list对象排序函数

在Java中,可以使用Collections类的sort()方法对List对象进行排序。以

下是一个示例代码:

```java

import ;

import ;

import ;

public class SortListExample {

public static void main(String[] args) {

List list = new ArrayList<>();

("apple");

("banana");

("orange");

("pear");

// 使用()方法对List进行排序

(list);

// 输出排序后的List

for (String str : list) {

(str);

}

}

}

```

输出结果为:

```

apple

banana

orange

pear

```

如果要对自定义对象进行排序,需要实现Comparable接口或提供一个

Comparator对象,然后将其传递给()方法。例如,如果要按对象的某个属

性进行排序,可以这样做:

```java

import ;

import ;

import ;

import ;

public class SortListExample {

public static void main(String[] args) {

List list = new ArrayList<>();

(new Fruit("apple", 10));

(new Fruit("banana", 5));

(new Fruit("orange", 8));

(new Fruit("pear", 7));

// 使用Comparator对象对List进行排序,按照Fruit对象的weight

属性升序排序

(list, new Comparator() {

Override

public int compare(Fruit f1, Fruit f2) {

return ((), ());

}

});

// 输出排序后的List

for (Fruit fruit : list) {

(() + " " + ());

}

}

}

```


发布者:admin,转转请注明出处:http://www.yc00.com/news/1718811905a2752785.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信