簡體   English   中英

高效的Java列表合並算法

[英]Efficient Java List Merging Algorithm

我有兩個Java列表(如在實際的類中一樣),每個列表都有一個編號列表和級別的元素,表示為String對象。 下面的每一行都是列表中的單獨字符串。 例如,第一個列表可以是:

==level 1==
1.1 2


==level 2==
1.R4 0
2.0 2


==level 3==
3.R3 1
4.R5 1

第二個可能是:

==level 3==
1.null
2.null

列表可以任意長度,數字后面的值在這里無關緊要。 目標是合並匹配級別的列表。 例如,上面兩個列表的合並將是:

==level 1==
1.1 2


==level 2==
1.R4 0
2.0 2


==level 3==
1.null
2.null
3.R3 1
4.R5 1

兩個列表的匹配級別中的數字將永遠不會相同,因此無需檢查。 我也相信這些數字將永遠是連續的。 到目前為止,這就是我所掌握的內容,但並不涵蓋所有情況,特別是當合並僅在某個級別的開始或僅在級別的結尾進行時。 看起來也很不愉快。 tempLines和line是兩個列表。

for(int x=0; x < lines.size();x++){
            for(int y=0; y < tempLines.size();y++){
                if(tempLines.get(y).equals(lines.get(x)) && !(tempLines.get(y).equals("\n"))&& !(lines.get(x).equals("\n"))){
                    int a=y+1;
                    int b=x+1;
                    while(!(tempLines.get(a).equals("\n"))){
                        while(!(lines.get(b).equals("\n"))){
                            if(Integer.valueOf(tempLines.get(a).charAt(0))==(Integer.valueOf(tempLines.get(a).charAt(0))-1))
                                lines.add(b,tempLines.get(a));
                        }
                    }
                }
            }
        }

有人可以幫忙嗎?

假設兩個輸入列表都按升序排序,則可以使用合並兩個排序列表/數組的標准方法。 要點是,您的算法不需要嵌套循環,而是交替瀏覽兩個列表,始終將較低的元素附加到結果中並在該列表中前進。 這是一個尊重數字和級別區別的草圖。

int ix_a = 0;
int ix_b = 0;
List<String> result = new ArrayList<String>();
while (ix_a < A.size() || ix_b < B.size()) {

    // No more elements in A => append everything from B to result
    if (ix_a == A.size()) {
        result.add(B.get(ix_b));
        ix_b++;
        continue;
    }

    // No more elements in B => append everything from A to result
    if (ix_b == B.size()) {
        result.add(A.get(ix_a));
        ix_a++;
        continue;
    } 

    // Always append the lower element and advance in that list. 
    // If both lists contain the same element, append this once and advance in both lists
    // Distinguish between levels and numbers here, levels take higher precedence.
    String a = A.get(ix_a);
    String b = B.get(ix_b);
    if (isLevel(a) && isLevel(b)) {
        if (isLowerLevel(a, b)) {
            result.add(a);
            ix_a++;
        } else if (isLowerLevel(b, a)) {
            result.add(b);
            ix_b++;
        } else {
            result.add(a);
            ix_a++;
            ix_b++;
        }
    } else if (isLevel(a)) {
        result.add(b);
        ix_b++;
    } else if (isLevel(b)) {
        result.add(a);
        ix_a++;
    } else {
        if (isLowerNumber(a, b)) {
            result.add(a);
            ix_a++;
        } else if (isLowerNumber(b, a)) {
            result.add(b);
            ix_b++;
        } else {
            result.add(a);
            ix_a++;
            ix_b++;
        }
    }
}

可以通過省略不必要的重復檢查(例如isLevel(...)isLevel(...)來進一步優化。此外,還必須添加對空行的處理。

我通常通過使用Map處理該問題。 可以使用其他集合,例如列表,但是我發現使用map的代碼更易於閱讀(除非您的列表中包含數百萬個元素,否則可能不會出現性能問題)。

在這種情況下,我將具有Map<Integer,String>來使條目保持正確的順序。 此類映射將作為值存儲在另一個映射中,其中鍵是級別編號。 我將使用TreeMap作為實現類,因為它根據條目的鍵對條目進行排序。

Map<Integer,Map<Integer,String>> map = new TreeMap<>();
int level=0; //current level
for (String line:templines) {
 if (line.startsWith("==level ")) { 
   level=Integer.valueOf(line.substring(7).replace("==","").trim());
   if (map.get(level)==null) map.put(level,new TreeMap<>());
 } else if (line.length>0) {
   int pos = line.indexOf('.');
   if (pos>0) {
    int n = Integer.valueOf(line.substring(0,pos));
    line=line.substring(pos+1);
    map.get(level).put(n,line); 
   }
 }
}

有了地圖后,我將對其進行迭代並將值保存在另一個列表中。

List<String> merged = new ArrayList<String>();
for (Map.Entry<Integer,Map<Integer,String>> entry:map.entrySet()) {
  list.add("==level "+entry.getKey()+"==");
  for (String line:entry.getValue().values()) {
   list.add(line);
  }
}

基本上,您將必須使用Map,其中將每個級別用作鍵,並將行列表作為值。 在完成要合並的列表的處理之后,獲取鍵集並對其進行降序排序,以便對級別進行排序。 然后,您可以開始使用已排序的鍵/級別遍歷地圖值。 在目標列表中添加級別,對實際級別對該列表進行排序,並將其所有元素也添加到目標中。

這是我想出的:

public class MergeLists {

    private final static String[] list1 = {
        "==level 1==\r\n", 
        "1.1 2\r\n", 
        "\r\n", 
        "\r\n", 
        "==level 2==\r\n", 
        "1.R4 0\r\n", 
        "2.0 2\r\n", 
        "\r\n", 
        "\r\n", 
        "==level 3==\r\n", 
        "3.R3 1\r\n", 
        "4.R5 1"
    };

    private final static String[] list2 = {
        "==level 3==\r\n", 
        "1.null\r\n", 
        "2.null"
    };

    @Test
    public void mergLists() {
        List<List<String>> listList = new ArrayList<>();
        listList.add(Arrays.asList(list1));
        listList.add(Arrays.asList(list2));
        List<String> mergedList = mergLists(listList);
        for(String s : mergedList) {
            System.out.println(s);
        }
    }

    public List<String> mergLists(List<List<String>> listList) {
        List<String> mergedList = new ArrayList<>();
        Map<String, List<String>> levelMap = new HashMap<String, List<String>>();
        for(int j = 0; j < listList.size(); j++) {
            List<String> list = listList.get(j);
            String actLevel = null;
            for(int i = 0; i < list.size(); i++) {
                String line = list.get(i).trim();
                if(isLevel(line)) {
                    actLevel = line;
                } else {
                    if(actLevel != null) {
                        List<String> levelList = levelMap.get(actLevel);
                        if(levelList == null) {
                            levelList = new ArrayList<>();
                            levelMap.put(actLevel, levelList);
                        }
                        levelList.add(line);
                    } else {
                        System.out.println("line " + (i+1) + " in list " + (j+1) + " does not belong to a level.");
                    }
                }
            }
        }

        List<String> sortedLevelList = new ArrayList<>(levelMap.keySet());
        Collections.sort(sortedLevelList, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return (extractNumberFromLevel(o1) - extractNumberFromLevel(o2));
            }

            private int extractNumberFromLevel(String level) {
                // check that this meets the format of your level entry (assuming "==level n==")
                int r = 0;
                int i = level.indexOf("level");
                if(i != -1) {
                    int j = level.lastIndexOf("==");
                    if(j != -1) {
                        String n = level.substring(i + "level".length(), j).trim();
                        try {
                            r = Integer.parseInt(n);
                        } catch(NumberFormatException e) {
                            // ignore and return 0
                        } 
                    }
                }
                return r;
            }
        });

        for(String level : sortedLevelList) {
            List<String> lineList = levelMap.get(level);
            Collections.sort(lineList, new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                    return o1.trim().length() == 0 ? 1 /* this puts the empty string at the end of the list */ 
                            : (extractNumberFromLine(o1) - extractNumberFromLine(o2));
                }

                private int extractNumberFromLine(String o) {
                    // check that this meets the format of your line entry (assuming "n.1 2")
                    int r = 0;
                    int i = o.indexOf('.');
                    if(i != -1) {
                        String n = o.substring(0, i).trim();
                        try {
                            r = Integer.parseInt(n);
                        } catch(NumberFormatException e) {
                            // ignore and return 0
                        }
                    }
                    return r;
                }
            });

            mergedList.add(level);
            mergedList.addAll(lineList);
        }

        return mergedList;
    }

    private boolean isLevel(String line) {
        // check that this meets the format of your level entry (assuming "==level n==")
        return line.contains("level");
    }
}

產量

==level 1==
1.1 2


==level 2==
1.R4 0
2.0 2


==level 3==
1.null
2.null
3.R3 1
4.R5 1

您可以按級別划分集合,並使用Apache Commons集合。

Collection a = createCollection();
Collection b = createCollection();

Collection c = CollectionUtils.union(a,b);

暫無
暫無

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

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