簡體   English   中英

使用HashMap對ArrayList進行字母數字排序

[英]Alphanumeric sorting of ArrayList with HashMap

我有一個ArrayList ,每個索引有幾個對象。 我想按一個對象的字母數字順序對該列表進行排序。 該對象為“ my_id”,該對象的值類似於:1A,10B,11B,2C,205Z等。

我需要對它們進行排序:1A,2C,10B,11B,205Z。 首先對數字部分進行排序,然后對alpha-部分進行排序。 1,2,3,4,5,... A,B,C,D,E,...

我檢查了一些效果很好的字母數字字符串排序: http : //sanjaal.com/java/206/java-data-structure/alphanumeric-string-sorting-in-java-implementation/

不幸的是,我只能使該對象排序,結果我失去了ArrayList的其他對象。 我確實需要一種排序算法,該算法可以按我選擇的對象重新排列ArrayList索引,而又不會丟失其他對象!

有沒有辦法做到這一點? 我一直找不到。 我認為添加ArrayList中的所有對象都是映射的字符串很有用: ArrayList<HashMap<String, String>>

[編輯]我有我的數組: ArrayList<HashMap<String, String>> al

然后,我存儲對象:

String[] alphaNumericStringArray = new String[al.size()];
        for(int i = 0; i < al.size(); i++)
        {
            alphaNumericStringArray[i] = al.get(i).get("my_id");
        }

我現在對字符串數組進行排序:

// Sort the array now.
        Arrays.sort(alphaNumericStringArray, new AlphanumericSorting());

然后,我把對象放回去:

for(int i = 0; i < al.size(); i++)
        {
            HashMap<String, String> map = new HashMap<String, String>();
                map.put("my_id", alphaNumericStringArray[i]);
                // TODO, need to append the rest of the objects.
            al.set(i, map);
        }

我知道您在想什么,當我重新映射它時,我並沒有添加所有對象。 這是我目前擁有的,但是我想要的是一種對整個列表進行排序的方法,而不僅僅是對一個對象“ my_id”進行排序。 我想重新排列索引,因此不必在最后重新映射所有內容。

運行main方法:

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

public class Sorter {

    public static void main(String[] args) {

        List<String> unsorted = Arrays.asList("1A", "10B", "B", "753c", "Z", "M7", "32x", "11B", "2C", "205Z");

        Collections.sort(unsorted, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {

                if (o1.isEmpty())
                    return -1;

                if (o2.isEmpty())
                    return 1;

                String o1number = extractNumberPrefix(o1);

                String o2number = extractNumberPrefix(o2);

                if (o1number.isEmpty())
                    if (o2number.isEmpty())
                        return o1.compareTo(o2);
                    else return 1;

                if (o2number.isEmpty())
                    return -1;

                if (o1number.equals(o2number))
                    return o1.compareTo(o2);

                return Integer.parseInt(o1number) - Integer.parseInt(o2number);
            }

            private String extractNumberPrefix(String o1) {

                String result = "";
                for (int i = 0; i < o1.length(); i++) {
                    try {
                        Integer.parseInt(o1.substring(i, i + 1));
                        result += o1.substring(i, i + 1);
                    } catch (Exception e) {
                        break;
                    }
                }
                return result;
            }
        });

        System.out.println("sorted = " + unsorted);
    }
}

返回:

sorted = [1A, 2C, 10B, 11B, 32x, 205Z, 753c, B, M7, Z]

在仔細比較了比較器和所有注釋之后,我終於找到了解決方法。

問題:重申我的目標是什么,以及解決方案。 我有一個ArrayList<HashMap<String, String>> 我想按HashMap中的一個對象對ArrayList進行排序。 我的HashMap中有多個對象,因此我想保留Array的整個索引。 我還想按字母數字排序,其中數值是最先排序的,而不是按字母順序排序。 即1,2,3,4,... A,B,C,D,...

參考: http : //sanjaal.com/java/206/java-data-structure/alphanumeric-string-sorting-in-java-implementation/

TL; DR解決方案:在我的自定義比較器函數public int compare(object firstObj, Object secondObj)我需要將String值更改為HashMap對象引用/值。 此處的KEY_ID是我要排序的對象。 完成此操作后,我使用Collections.sort按HashMap比較器而不是Arrays.sort(Collections處理ArrayList / HashMaps)進行排序。

代碼解決方案:

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

/** 
 * DOCUMENTATION: 
 * http://sanjaal.com/java/206/java-data-structure/alphanumeric-string-sorting-in-java-implementation/ 
 **/

@SuppressWarnings({"rawtypes", "unchecked"})
public class AlphanumericSorting implements Comparator 
{
    public int compare(Object firstObjToCompare, Object secondObjToCompare) 
    {
        String firstString  = ((HashMap<String,String>) firstObjToCompare).get("KEY_ID");
        String secondString = ((HashMap<String,String>) secondObjToCompare).get("KEY_ID");

        //String firstString    = firstObjToCompare.toString();
        //String secondString = secondObjToCompare.toString();

        if (secondString == null || firstString == null) 
        {
            return 0;
        }

        int lengthFirstStr  = firstString.length();
        int lengthSecondStr = secondString.length();

        int index1 = 0;
        int index2 = 0;

        while(index1 < lengthFirstStr && index2 < lengthSecondStr) 
        {
            char ch1 = firstString.charAt(index1);
            char ch2 = secondString.charAt(index2);

            char[] space1 = new char[lengthFirstStr];
            char[] space2 = new char[lengthSecondStr];

            int loc1 = 0;
            int loc2 = 0;

            do 
            {
                space1[loc1++] = ch1;
                index1++;

                if (index1 < lengthFirstStr) 
                {
                    ch1 = firstString.charAt(index1);
                } 
                else 
                {
                    break;
                }
            } 
            while (Character.isDigit(ch1) == Character.isDigit(space1[0]));

            do 
            {
                space2[loc2++] = ch2;
                index2++;

                if (index2 < lengthSecondStr) 
                {
                    ch2 = secondString.charAt(index2);
                } else 
                {
                    break;
                }
            } 
            while (Character.isDigit(ch2) == Character.isDigit(space2[0]));

            String str1 = new String(space1);
            String str2 = new String(space2);

            int result;

            if (Character.isDigit(space1[0]) && Character.isDigit(space2[0])) 
            {
                Integer firstNumberToCompare    = new Integer(Integer.parseInt(str1.trim()));
                Integer secondNumberToCompare   = new Integer(Integer.parseInt(str2.trim()));

                result = firstNumberToCompare.compareTo(secondNumberToCompare);
            } 
            else 
            {
                result = str1.compareTo(str2);
            }

            if (result != 0) 
            {
                return result;
            }
        }

        return lengthFirstStr - lengthSecondStr;
    }

    /**
     * ALPHANUMERIC SORTING
     */
    public static ArrayList<HashMap<String, String>> sortArrayList(ArrayList<HashMap<String, String>> al)
    {
        Collections.sort(al, new AlphanumericSorting());

        return al;
    }
}

要返回已排序的ArrayList:

myArrayList = AlphanumericSorting.sortArrayList(myArrayList);

哪里,

ArrayList<HashMap<String, String>> myArrayList;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM