两个ArrayLists之间的同步排序

Rya*_*tts 3 java sorting collections arraylist

我有两个ArrayLists.

  • 第一个包含一组带有大写和标点符号的单词.

  • 另一个包含同一组词,但删除了大写和标点符号.

.

ArrayList1 ..... ArrayList2

MURDER! ........ murder

It's ........... its

Hello .......... hello

Yes-Man ........ yesman

ON ............. on
Run Code Online (Sandbox Code Playgroud)

第二个数组具有按字母顺序排列的所有单词,并且每个单词中的所有字母都按字母顺序排列.它看起来像这样:

aemnsy
demrru
ehllo
ist
no
Run Code Online (Sandbox Code Playgroud)

我想这样做,以便当我将ArrayList中的单词排列成字母顺序时,所有来自ArrayList的单词都遵循套件:

ArrayList1 ..... ArrayList2

Yes-Man ........ aemnsy

MURDER! ........ demrru

Hello .......... ehllo

It's ........... ist

ON ............. no
Run Code Online (Sandbox Code Playgroud)

我尝试用一​​个或两个for语句创建一个循环,但它最终没有工作并变得很长.我该怎么做呢?我该如何有效地做到这一点?

bco*_*rso 5

这是一个基于单个"键"列表对多个列表进行排序的功能.该名单并不需要是同一类型,这里的关键列表类型String和它被用来排序String,Integer以及Double列表(Ideone例):

List<String> key = Arrays.asList("demrru", "ist", "ehllo", "aemnsy", "no");
List<String> list1 = Arrays.asList("MURDER!","It's", "Hello","Yes-Man", "ON");
List<Integer> list2 = Arrays.asList(2, 4, 3, 1, 5);            // Also use Integer type 
List<Double>  list3 = Arrays.asList(0.2, 0.4, 0.3, 0.1, 0.5);  // or Double type

// Sort all lists (excluding the key)
keySort(key, list1, list2, list3);

// Sort all lists (including the key)
keySort(key, key, list1, list2, list3);
Run Code Online (Sandbox Code Playgroud)

输出:

// Sorted by key:
[Yes-Man, MURDER!, Hello, It's, ON]
[aemnsy, demrru, ehllo, ist, no]
[1, 2, 3, 4, 5]
[0.1, 0.2, 0.3, 0.4, 0.5]
Run Code Online (Sandbox Code Playgroud)

排序功能

这里可以找到Ideone示例,其中包括参数验证和测试用例.

public static <T extends Comparable<T>> void keySort(
                                        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.
    Map<Integer,Integer> swapMap = new HashMap<Integer, Integer>(indices.size());

    // Only swaps can be used b/c we cannot create a new List of type <?>
    for(int i = 0; i < indices.size(); i++){
        int k = indices.get(i);
        while(swapMap.containsKey(k))
            k = swapMap.get(k);

        swapMap.put(i, k);
    }

    // for each list, swap elements to sort according to key list
    for(Map.Entry<Integer, Integer> e : swapMap.entrySet())
        for(List<?> list : lists)
            Collections.swap(list, e.getKey(), e.getValue());
}
Run Code Online (Sandbox Code Playgroud)