You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何按首个数值对ArrayList进行数值排序(忽略第二个数字)

Ah, I see the problem here! The default Collections.sort() for String uses lexicographical order, which doesn't match numerical order when your values have different digit lengths. For example, "10 1" will come before "9 2" lexicographically (since '1' < '9'), but numerically 9 is smaller than 10—so your sorted list ends up out of order.

方案1:自定义Comparator排序现有String列表

You can pass a custom comparator to Collections.sort() that extracts the numerical part of each string for proper numeric comparison. This doesn't require changing how you store data, just modifying the sorting step:

Collections.sort(temp, (s1, s2) -> {
    // Extract the first 10 characters (your fixed-length value section), trim spaces, convert to integer
    int num1 = Integer.parseInt(s1.substring(0, 10).trim());
    int num2 = Integer.parseInt(s2.substring(0, 10).trim());
    // Sort in ascending numerical order; use Integer.compare(num2, num1) for descending
    return Integer.compare(num1, num2);
});

This leverages your existing fixed-length value formatting, making it more efficient than splitting strings and perfectly aligned with your current code structure.

方案2:Use a Custom Object for Data (Better Long-Term Solution)

For better code maintainability and readability, encapsulating the value and source flag into a custom object is a smarter choice—it avoids potential issues with string parsing and makes the logic clearer.

First, create a simple data class:

class DataEntry {
    private int value;
    private int sourceFlag;

    public DataEntry(int value, int sourceFlag) {
        this.value = value;
        this.sourceFlag = sourceFlag;
    }

    public int getValue() {
        return value;
    }

    // Override toString to generate your desired formatted string
    @Override
    public String toString() {
        String valueStr = Integer.toString(value);
        StringBuilder sb = new StringBuilder(valueStr);
        // Pad with spaces to reach 10 characters
        while (sb.length() < 10) {
            sb.append(" ");
        }
        sb.append(sourceFlag);
        return sb.toString();
    }
}

Then modify your original code to use ArrayList<DataEntry> instead of ArrayList<String>:

public void xor(arrayObject[] array){
 try{
 FileWriter textWriter = new FileWriter(new File("xor.txt"));
 ArrayList<DataEntry> temp = new ArrayList<>();
 for(int i = 0; i < array.length; i++){
 if(array[i] != null){
 int hash = hashFunction(i);
 if(array[hash].foundFromA && !array[hash].foundFromB){
 temp.add(new DataEntry(array[hash].value, 1));
 } else if(!array[hash].foundFromA && array[hash].foundFromB){
 temp.add(new DataEntry(array[hash].value, 2));
 }
 }
 }
 // Sort by numerical value in ascending order
 Collections.sort(temp, Comparator.comparingInt(DataEntry::getValue));
 for(DataEntry entry : temp){
 textWriter.write(entry.toString());
 textWriter.write(System.lineSeparator());
 }
 textWriter.close();
 System.out.println("Writing xor file succesful");
 } catch(IOException e){
 System.out.println("Failed to save file");
 }
 }

This approach makes your code more object-oriented, eliminates manual string concatenation, and ensures sorting behaves exactly as you expect by comparing the raw numeric values directly.

内容的提问来源于stack exchange,提问作者Eckersley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:57:18