2011-08-10 199 views
1

假設我有以下列表:如何將列表中的兩個項目合併爲一個?

A | B | C | Dthe | temperature | is | 100 | °F | today

我想兩個屬性合併爲一個,這樣的事情:

A | BC | Dthe | temperature | is | 100°F | today

我怎樣才能做到這一點?如果需要,可以更改集合。

+2

那麼,你在哪個部分掙扎,似乎是一個非常簡單的事情呢? – R0MANARMY

+0

舉個更多的例子。爲什麼你合併'BC'和'100°F'?什麼規則支配這一點? –

+0

@ J-16 SDiz這兩個只是例子,合併這個規則並不重要。我的疑問只是如何合併這兩個項目。可以換個話說。 –

回答

4

,如果你的努力做的是採取一個元素,它的後繼者,並把它們合併,這應該工作:

String i = list.get(iIndex); 
String j = list.get(iIndex + 1); 
i= i.concat(j); 
list.set(iIndex,i); 
list.remove(iIndex + 1); 
+0

這假定只有相鄰的元素需要合併。不知道這是OP想要的。 –

+0

@Pangea是的,目前,只有下一個或上一個元素需要合併(如果匹配一些規則) –

+0

@Renato DinhaniConceição此代碼只處理與下一個元素的合併。您可以將以前的行爲添加到此代碼中,也可以使用我提供的通用代碼(您需要稍微修改它以處理錯誤情況)。雖然 –

1

我很驚訝,沒有標準的API的方法來做到這一點。哦,這是我家釀的解決方案:

public static void main(String[] args) { 
    final List<String> fruits = Arrays.asList(new String[] { "Apple", "Orange", "Pear", "Banana" }); 
    System.out.println(fruits); // Prints [Apple, Orange, Pear, Banana] 
    System.out.println(merge(fruits, 1)); // Prints [Apple, OrangePear, Banana] 
    System.out.println(merge(fruits, 3)); // Throws java.lang.IndexOutOfBoundsException: Cannot merge last element 
} 

public static List<String> merge(final List<String> list, final int index) { 
    if (list.isEmpty()) { 
     throw new IndexOutOfBoundsException("Cannot merge empty list"); 
    } else if (index + 1 >= list.size()) { 
     throw new IndexOutOfBoundsException("Cannot merge last element"); 
    } else { 
     final List<String> result = new ArrayList<String>(list); 
     result.set(index, list.get(index) + list.get(index + 1)); 
     result.remove(index + 1); 
     return result; 
    } 
} 
0

這裏沒有直接的api。但下面可以讓你開始

import java.util.ArrayList; 
import java.util.List; 

public class Test { 

    static List<String> list = new ArrayList<String>(); 

    /** 
    * @param toIndex the index of the element that other items are merged with. The final merged item is set at this index. 
    * @param indices a comma separated list of indices of the items that need be merged with item at <code>toIndex</code> 
    */ 
    public static void merge(int toIndex, int... indices) { 
     StringBuilder sb = new StringBuilder(list.get(toIndex)); 
     for (int i = 0; i < indices.length; i++) { 
      sb.append(list.get(indices[i])); 
     } 
     for (int i = 0; i < indices.length; i++) { 

      list.remove(indices[i]); 
     } 
     list.set(toIndex, sb.toString()); 
    } 

    public static void main(String[] args) { 
     list.add("A"); 
     list.add("B"); 
     list.add("C"); 
     list.add("D"); 
     merge(1,2); 
     System.out.println(list); 
    } 

} 
+0

的概念是相同的,但是如果要將索引i ... j合併到k中使得k> i ... j?刪除索引會不會移動後續列表項的索引號? – wespiserA

+0

嘗試合併(3,2),它應該會拋出一個不錯的java.lang.IndexOutOfBoundsException – wespiserA

+1

wespiserA - 您的兩個擔心都是有效的,但是SO旨在提供提示而不是完整的生產就緒解決方案。 –