簡體   English   中英

如何在java中對多個數組進行排序

[英]How to sort multiple arrays in java

我試圖按字典順序對三個數組進行排序。 陣列通過公共陣列彼此相關。 如果我證明,它更容易解釋:

int[] record = new int[4];
String [] colors = {"blue", "yellow", "red", "black"};
String [] clothes = {"shoes", "pants", "boots", "coat"};

在控制台上打印時,我希望將它們放在類似下面的三列中:

未排序:

Record  Color   Clothes
0       blue    shoes
1       yellow  pants
2       red     boots
3       black   coat

按顏色排序:

Record  Color   Clothes
3       black   coat
0       blue    shoes
2       red     boots
1       yellow  pants

按衣服排序:

Record  Color   Clothes
2       red     boots
3       black   coat
1       yellow  pants
0       blue    shoes

我找到了一個類似於我的場景的先前答案,但是它比較了整數而不是字符串,而我在使用compareTo()方法和Arrays.sort()來達到我想要的輸出時遇到了麻煩。

任何幫助,將不勝感激!

在某些情況下,創建一個新類只是為了進行排序沒有多大意義。

這里,是一個函數,可用於根據鍵列表( List<T implements Comparable> )對任意數量的任意類型列表( List<?> )進行排序。 這里是Ideone示例


用法

下面是一個如何使用該函數對任意類型的多個列表進行排序的示例:

List<Integer> ids = Arrays.asList(0, 1, 2, 3);
List<String> colors = Arrays.asList("blue", "yellow", "red", "black");
List<String> clothes = Arrays.asList("shoes", "pants", "boots", "coat");

// Sort By ID
concurrentSort(ids, ids, colors, clothes);

// Sort By Color
concurrentSort(colors, ids, colors, clothes);

// Sort By Clothes
concurrentSort(clothes, ids, colors, clothes);

輸出:

// Sorted By ID:
ID:      [0, 1, 2, 3]
Colors:  [blue, yellow, red, black]
Clothes: [shoes, pants, boots, coat]

// Sorted By Color:
ID:      [3, 0, 2, 1]
Colors:  [black, blue, red, yellow]
Clothes: [coat, shoes, boots, pants]

// Sorted By Clothes:
ID:      [2, 3, 1, 0]
Colors:  [red, black, yellow, blue]
Clothes: [boots, coat, pants, shoes]

這里可以找到Ideone示例其中包括參數驗證和測試用例。

public static <T extends Comparable<T>> void concurrentSort(
                                        final List<T> key, List<?>... lists){
    // Create a List of indices
    List<Integer> indices = new ArrayList<Integer>();
    for(int i = 0; i < key.size(); i++)
        indices.add(i);

    // Sort the indices list based on the key
    Collections.sort(indices, new Comparator<Integer>(){
        @Override public int compare(Integer i, Integer j) {
            return key.get(i).compareTo(key.get(j));
        }
    });

    // Create a mapping that allows sorting of the List by N swaps.
    // Only swaps can be used since we do not know the type of the lists
    Map<Integer,Integer> swapMap = new HashMap<Integer, Integer>(indices.size());
    List<Integer> swapFrom = new ArrayList<Integer>(indices.size()),
                  swapTo   = new ArrayList<Integer>(indices.size());
    for(int i = 0; i < key.size(); i++){
        int k = indices.get(i);
        while(i != k && swapMap.containsKey(k))
            k = swapMap.get(k);

        swapFrom.add(i);
        swapTo.add(k);
        swapMap.put(i, k);
    }

    // use the swap order to sort each list by swapping elements
    for(List<?> list : lists)
        for(int i = 0; i < list.size(); i++)
            Collections.swap(list, swapFrom.get(i), swapTo.get(i));
}

注意:運行時間為O(mlog(m) + mN) ,其中m是列表的長度, N是列表的數量。 通常m >> N所以運行時間並不比僅排序鍵O(mlog(m))更重要。

由於RecordColorClothes似乎屬於一體,我建議將它們放在一個自定義對象中,例如

public class ClothesItem {
    int record;
    String color;
    String clothes;
}  

然后你可以讓不同的Comparator來做不同的排序變種。

如果您需要使用多個數組保留當前結構, @ Jackson在這里有一個排序解決方案,它可以獲得一系列已排序的索引,這樣可以輕松獲得您想要的結果。

好吧,這是最終形式的樣子。

// ColorClothes.java

import java.util.*;


public class ColorClothes
{
public int record;
public String color;
public String clothes;

public static void main(String[] args)
{
    Initialize();
}

public ColorClothes(int record, String color, String clothes)
{
    this.record = record;
    this.color = color;
    this.clothes = clothes;
}

public static void Initialize()
{
    List<ColorClothes> list = new ArrayList();
    list = CreateList();

    Sort(list, "Unsorted", 1);
    Sort(list, "\nSortedByColor", 2);
    Sort(list, "\nSortedByClothes", 3);
    Sort(list, "\nSortedByRecord", 4);
}


public static List<ColorClothes> CreateList()
{
    List<ColorClothes> list = new ArrayList();
    list.add(new ColorClothes(1, "blue  ", "shoes"));
    list.add(new ColorClothes(0, "yellow", "pants"));
    list.add(new ColorClothes(3, "red   ", "boots"));
    list.add(new ColorClothes(2, "black ", "coat"));

    return list;
}

public static void Print(List<ColorClothes> list)
{
    for (ColorClothes item : list)
    {
        System.out.println(item.record + "    " + item.color + "   " + item.clothes);
    }
}

public static void Sort(List<ColorClothes> list, String string, int choice)
{
    System.out.println(string + "\n");

    switch (choice)
    {
    case 1:
        break;
    case 2:
        Collections.sort(list, new ColorComparator());
        break;
    case 3:
        Collections.sort(list, new ClothesComparator());
        break;
    case 4:
        Collections.sort(list, new RecordComparator());
        break;
    }

    Print(list);
}

} // End class.

// ColorComparator.java

import java.util.Comparator;

 class ColorComparator implements Comparator
 {
public int compare(Object str1, Object str2)
{
    String str1Color = ((ColorClothes)str1).color;
    String str2Color = ((ColorClothes)str2).color;

    return str1Color.compareTo(str2Color);

}
}// End class.

// ClothesComparator.java

import java.util.Comparator;


class ClothesComparator implements Comparator
{
public int compare(Object str1, Object str2)
{
    String str1Clothes = ((ColorClothes)str1).clothes;
    String str2Clothes = ((ColorClothes)str2).clothes;

    return str1Clothes.compareTo(str2Clothes);

}
} // End class.

// RecordComparator.java

import java.util.Comparator;


public class RecordComparator implements Comparator 
{
public int compare(Object rec1, Object rec2)
{
    int rec1Rec = ((ColorClothes)rec1).record;
    int rec2Rec = ((ColorClothes)rec2).record;

    if(rec1Rec > rec2Rec)
    {
        return 1;
    }
    else if(rec1Rec < rec2Rec)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}
}// End class.

控制台輸出

Unsorted

1    blue     shoes
0    yellow   pants
3    red      boots
2    black    coat

SortedByColor

2    black    coat
1    blue     shoes
3    red      boots
0    yellow   pants

SortedByClothes

3    red      boots
2    black    coat
0    yellow   pants
1    blue     shoes

SortedByRecord

0    yellow   pants
1    blue     shoes
2    black    coat
3    red      boots

我不確定一次排序多個數組; 查看您使用的用例,這看起來像一個競爭者,其中所有3個屬性可以組合成一個對象,然后對象數組可以以多種方式排序。

你確定需要3個陣列嗎?

ColoredCloth數組是否適用於您:

class ColoredCloth implements Comparable<ColoredCloth>{
    int id;
    String color;
    String cloth;
}

並定義幾個Comparatorscolorcloth排序。

直接對數組進行排序。 索引所有數組並僅排序所需數組的索引數組。 看看這篇SO帖子中的解決方案。 這將使您的陣列保持一致。 我不確定是否可以很容易地將其推斷為同步排序N陣列,但它應該讓您了解如何解決問題,以防您希望將數據分布在多個陣列中。 正如幾位人士已經指出的那樣,將數據分組到一個對象中是一種很好的方法。

下面是我如何對兩個或多個相同長度的字符串數組進行排序,以便第一個數組按順序排列,其他數組與該順序匹配:

public static void order(String[]... arrays)
{
    //Note: There aren't any checks that the arrays
    // are the same length, or even that there are
    // any arrays! So exceptions can be expected...
    final String[] first = arrays[0];

    // Create an array of indices, initially in order.
    Integer[] indices = ascendingIntegerArray(first.length);

    // Sort the indices in order of the first array's items.
    Arrays.sort(indices, new Comparator<Integer>()
        {
            public int compare(Integer i1, Integer i2)
            {
                return
                    first[i1].compareToIgnoreCase(
                    first[i2]);
            }
        });

    // Sort the input arrays in the order
    // specified by the indices array.
    for (int i = 0; i < indices.length; i++)
    {
        int thisIndex = indices[i];

        for (String[] arr : arrays)
        {
            swap(arr, i, thisIndex);
        }

        // Find the index which references the switched
        // position and update it with the new index.
        for (int j = i+1; j < indices.length; j++)
        {
            if (indices[j] == i)
            {
                indices[j] = thisIndex;
                break;
            }
        }
    }
    // Note: The indices array is now trashed.
    // The first array is now in order and all other
    // arrays match that order.
}

public static Integer[] ascendingIntegerArray(int length)
{
    Integer[] array = new Integer[length];
    for (int i = 0; i < array.length; i++)
    {
        array[i] = i;
    }
    return array;
}

public static <T> void swap(T[] array, int i1, int i2)
{
    T temp = array[i1];
    array[i1] = array[i2];
    array[i2] = temp;
}

如果你想用其他類型的數組做這個,那么你需要稍微重構一下。 或者,對於要與字符串數組一起排序的整數數組,可以將整數轉換為字符串。

我建議你創建一個類,如下所示

class Dress {
  public int record;
  public String color;
  public String clothes;
}

保持禮服清單如下

List<Dress> dressCollection = new ArrayList<Dress>();

根據顏色和衣服實施比較器。

List<Dress> resultBasedOnColor = Collections.sort(dressCollection, new Comparator<Dress>() {
   public int compareTo(Dress obj1, Dress obj2) {
     return obj1.color.compareTo(obj2.color);
 }

});

基於衣服的左排序作為問題所有者的練習。

將數據放入像@SiB這樣的自定義類中:

class ColoredClothes {
    int id;
    String color;
    String cloth;
}

然后,將此類的每個實例放入一個以顏色作為鍵的TreeMap(或根據您要排序的布料名稱):

TreeMap<String,ColoredClothes> sortedCloth= new TreeMap<String,ColoredClothes>();
//loop through arrays and put new ColoredClothes into Map

然后獲取排序值,如下所示:

Collection<ColoredClothes> values = sortedCloth.values();

您可以使用values.iterator()按順序遍歷這些

謝謝你的幫助。

我是如此固定使用數組並對這些數組進行排序(因為這是我所需要的),我甚至沒有考慮過創建對象。

使用這個簡單的程序,它將允許您創建一個對象並對對象中的字段進行排序。 顏色和衣服只是我使用的一個例子。

這是我在下面完成的代碼:

// ColorClothes.java

import java.util.*;


public class ColorClothes
{
public int record;
public String color;
public String clothes;

public static void main(String[] args)
{
    Initialize();
}

public static void Initialize()
{
    ColorClothes item[] = new ColorClothes[4];

    item[0] = new ColorClothes();
    item[0].record = 0;
    item[0].color = "blue";
    item[0].clothes = "shoes";

    item[1] = new ColorClothes();
    item[1].record = 1;
    item[1].color = "yellow";
    item[1].clothes = "pants";

    item[2] = new ColorClothes();
    item[2].record = 2;
    item[2].color = "red";
    item[2].clothes = "boots";

    item[3] = new ColorClothes();
    item[3].record = 3;
    item[3].color = "black";
    item[3].clothes = "coat";

    System.out.println("Unsorted");

    for(int i = 0; i < item.length; i++)
    {
        System.out.println(item[i].record + "     " + item[i].color + "     " + item[i].clothes);
    }

    System.out.println("\nSorted By Color\n");

    Arrays.sort(item, new ColorComparator());

    for(int i = 0; i < item.length; i++)
    {
        System.out.println(item[i].record + "     " + item[i].color + "     " + item[i].clothes);
    }

    System.out.println("\nSorted By Clothes\n");

    Arrays.sort(item, new ClothesComparator());

    for(int i = 0; i < item.length; i++)
    {
        System.out.println(item[i].record + "     " + item[i].color + "     " + item[i].clothes);
    }

}

}// End class.

// ColorComparator.java

import java.util.Comparator;

class ColorComparator implements Comparator
{
public int compare(Object str1, Object str2)
{
    String str1Color = ((ColorClothes)str1).color;
    String str2Color = ((ColorClothes)str2).color;

    return str1Color.compareTo(str2Color);

}
}// End class.

// ClothesComparator.java

import java.util.Comparator;


class ClothesComparator implements Comparator
{
public int compare(Object str1, Object str2)
{
    String str1Clothes = ((ColorClothes)str1).clothes;
    String str2Clothes = ((ColorClothes)str2).clothes;

    return str1Clothes.compareTo(str2Clothes);

}
} // End class.

控制台輸出

Unsorted
0     blue     shoes
1     yellow     pants
2     red     boots
3     black     coat

Sorted By Color

3     black     coat
0     blue     shoes
2     red     boots
1     yellow     pants

Sorted By Clothes

2     red     boots
3     black     coat
1     yellow     pants
0     blue     shoes

我將添加另一個Comparator,以便稍后按記錄/整數進行排序。 我還會更加濃縮代碼,因此它不是一個大塊,但我幾乎完成了當天的工作。

正如其他人所建議的那樣,更容易對對象進行排序,而不是同步對三個數組進行排序。

如果由於某種原因你必須堅持排序多個數組,可以使用以下方法 - 想法是實現自己的數組列表變體,它由三個數組而不是一個數組支持

import java.util.AbstractList;
import java.util.Collections;

public class SortMultipleArrays extends AbstractList {

    //object representing tuple from three arrays
    private static class ClothesItem implements Comparable<ClothesItem> {
        int record;
        String color;
        String clothes;

        public ClothesItem(int record, String color, String clothes) {
            this.record = record;
            this.color = color;
            this.clothes = clothes;
        }

        @Override
        public int compareTo(ClothesItem o) {
            return this.color.compareTo(o.color); //sorting by COLOR
        }
    }

    private int[] records;
    private String[] colors;
    private String[] clothes;

    public SortMultipleArrays(int[] records, String[] colors, String[] clothes) {
        this.records = records;
        this.colors = colors;
        this.clothes = clothes;
    }

    @Override
    public Object get(int index) {
        return new ClothesItem(records[index], colors[index], clothes[index]);
    }

    @Override
    public int size() {
        return records.length;
    }

    @Override
    public Object set(int index, Object element) {
        ClothesItem item = (ClothesItem) element;
        ClothesItem old = (ClothesItem) get(index);

        records[index] = item.record;
        colors[index] = item.color;
        clothes[index] = item.clothes;

        return old;
    }

    public static void main(String[] args) {
        int[] record = {0,1,2,3};
        String[] colors = {"blue", "yellow", "red", "black"};
        String[] clothes = {"shoes", "pants", "boots", "coat"};

        final SortMultipleArrays multipleArrays = new SortMultipleArrays(record, colors, clothes);
        Collections.sort(multipleArrays);

        System.out.println("Record  Color   Clothes");
        for (int i = 0; i < record.length; i++) {
            System.out.println(String.format("%8s %8s %8s", record[i], colors[i], clothes[i]));
        }
    }
}

此實現基於AbstractList,這使得更容易實現Collections.sort(...)所需的List接口。

請注意,此實現中可能隱藏效率低: get(...)set(...)方法都在創建包裝器對象的實例,這可能導致在排序較大的數組時創建的對象太多。

喜歡@ bcorso創建交換列表來排序任何其他List的想法。 這是一個更優化的版本,它只使用2個數組而不是Map和3個ListArrays,只交換需要交換的索引:

public static <T extends Comparable<T>> void syncedSort(final List<T> key, List<?>... lists) {
    // Create an array of indices
    Integer[] indices = new Integer[key.size()];
    for (int i = 0; i < indices.length; i++)
        indices[i] = i;

    // Sort the indices array based on the key
    Arrays.sort(indices, new Comparator<Integer>() {
        @Override public int compare(Integer i, Integer j) {
            return key.get(i).compareTo(key.get(j));
        }
    });

    // Scan the new indices array and swap items to their new locations,
    // while remembering where original items stored.
    // Only swaps can be used since we do not know the type of the lists
    int[] prevSwaps = new int[indices.length];
    for (int i = 0; i < indices.length; i++) {
        int k = indices[i];
        while (i > k)
            k = prevSwaps[k];
        if (i != k) {
            prevSwaps[i] = k;
            for (List<?> list : lists)
                Collections.swap(list, i, k);
        }
    }
}
import java.util.Arrays;

Arrays.sort (int [])
Arrays.sort (String [])

這將排序字符串數組。

暫無
暫無

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

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