java List集合排序

该代码示例展示了如何使用Collections.sort方法对一个包含BluetoothDevice对象的列表进行排序。BluetoothDevice对象根据其信号强度属性进行排序,可以实现从小到大或从大到小的排序。在测试中,确保排序后的第一个设备名称为'蓝牙7'。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用Collections.sort进行排序

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

public class SetSortTools {
    public static List<BluetoothDevice> getListBluetoothDevice(){
        List<BluetoothDevice> bluetoothDeviceList=new ArrayList<>();
        bluetoothDeviceList.add(getBluetoothDevice("蓝牙1","xxx-xx-xx-xx-x-1",13));
        bluetoothDeviceList.add(getBluetoothDevice("蓝牙2","xxx-xx-xx-xx-x-1",14));
        bluetoothDeviceList.add(getBluetoothDevice("蓝牙7","xxx-xx-xx-xx-x-1",20));
        bluetoothDeviceList.add(getBluetoothDevice("蓝牙3","xxx-xx-xx-xx-x-1",16));
        bluetoothDeviceList.add(getBluetoothDevice("蓝牙4","xxx-xx-xx-xx-x-1",17));
        bluetoothDeviceList.add(getBluetoothDevice("蓝牙5","xxx-xx-xx-xx-x-1",17));
        bluetoothDeviceList.add(getBluetoothDevice("蓝牙6","xxx-xx-xx-xx-x-1",18));
        return bluetoothDeviceList;
    }
    private static BluetoothDevice getBluetoothDevice(String name,String address,int strength){
        BluetoothDevice mBluetoothDevice=new BluetoothDevice();
        mBluetoothDevice.setName(name);
        mBluetoothDevice.setAddress(address);
        mBluetoothDevice.setStrength(strength);
        return mBluetoothDevice;
    }
    public static List<BluetoothDevice> sortBluetoothList(List<BluetoothDevice> bluetoothDeviceList){
        Collections.sort(bluetoothDeviceList, new Comparator<BluetoothDevice>() {
            @Override
            public int compare(BluetoothDevice o1, BluetoothDevice o2) {
                //正序 从小到大排列
                //return o1.getStrength()-o2.getStrength();
                //倒序 从大到小排列
                return o2.getStrength()-o1.getStrength();
            }
        });
        for (int i = 0; i < bluetoothDeviceList.size(); i++) {
            System.out.println(bluetoothDeviceList.get(i).getName()+"===="+bluetoothDeviceList.get(i).getStrength()+"");
        }
        return bluetoothDeviceList;
    }
}

调用

assertEquals("蓝牙7", SetSortTools.sortBluetoothList(SetSortTools.getListBluetoothDevice()).get(0).getName())

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值