代码改变世界

Java List集合中元素比较大小

  默默不语  阅读(11231)  评论(0编辑  收藏  举报

list排序方法一Comparator形式:

1.比较数字

复制代码
List<Shoes> all_shoes = new ArrayList<Shoes>();
Collections.sort(all_shoes, new Comparator<Shoes>(){
    @Override
    /* *
     * int compare(String o1, String o2) 返回一个基本类型的整型
     * 返回-1表示:shoes1.getSimilarity()大于等于shoes2.getSimilarity(),
     * 返回1表示:shoes1.getSimilarity()小于shoes2.getSimilarity(),              
     * */
    public int compare(Shoes shoes1, Shoes shoes2) {
        if (shoes1.getSimilarity()<shoes2.getSimilarity()){
            return 1;
        }else{
            return -1;
        }
    }
});
System.out.println("比较后");
for(Shoes s:all_shoes) {
    System.out.println(s.getId());
    System.out.println(s.getShoes_name());
    System.out.println(s.getPrice());
    System.out.println(s.getDeal());
    System.out.println(s.getImage());
    System.out.println(s.getShop_name());
    System.out.println(s.getAddress());
    System.out.println(s.getUrl());
    System.out.println(s.getSource());
    System.out.println(s.getSimilarity());
    System.out.println("--------------------------");
}
复制代码

运行结果(similarity按从大到小顺序排列):

2.字符串型

复制代码
package dao;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
*@author chenmeiqi
*@version 2020年2月24日 下午12:13:17
*/
public class test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List<String> keyList = new ArrayList<>();
        keyList.add("abc");
        keyList.add("fgh");
        keyList.add("cvb");
        System.out.println("排序前:");
        for(String s:keyList) {
            System.out.println(s);
        }
        
        Collections.sort(keyList, new Comparator<String>(){
            @Override
            public int compare(String o1, String o2) {
                /*
                 * * int compare(String o1, String o2) 返回一个基本类型的整型,
                 * * 返回负数表示:o1 小于o2,
                 * * 返回0 表示:o1和o2相等,
                 * * 返回正数表示:o1大于o2
                 * */
                if (o1.compareTo(o2) > 0){
                    return 1;
                }else if (o1.compareTo(o2) > 0){
                    return 0;
                }else{
                    return -1;
                }
            }
        });
        System.out.println("排序后:");
        for(String s:keyList) {
            System.out.println(s);
        }

    }

}
复制代码

运行结果:

编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示