假設我有以下列表:如何將列表中的兩個項目合併爲一個?
A | B | C | D
或the | temperature | is | 100 | °F | today
我想兩個屬性合併爲一個,這樣的事情:
A | BC | D
或the | temperature | is | 100°F | today
我怎樣才能做到這一點?如果需要,可以更改集合。
假設我有以下列表:如何將列表中的兩個項目合併爲一個?
A | B | C | D
或the | temperature | is | 100 | °F | today
我想兩個屬性合併爲一個,這樣的事情:
A | BC | D
或the | temperature | is | 100°F | today
我怎樣才能做到這一點?如果需要,可以更改集合。
,如果你的努力做的是採取一個元素,它的後繼者,並把它們合併,這應該工作:
String i = list.get(iIndex);
String j = list.get(iIndex + 1);
i= i.concat(j);
list.set(iIndex,i);
list.remove(iIndex + 1);
這假定只有相鄰的元素需要合併。不知道這是OP想要的。 –
@Pangea是的,目前,只有下一個或上一個元素需要合併(如果匹配一些規則) –
@Renato DinhaniConceição此代碼只處理與下一個元素的合併。您可以將以前的行爲添加到此代碼中,也可以使用我提供的通用代碼(您需要稍微修改它以處理錯誤情況)。雖然 –
我很驚訝,沒有標準的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;
}
}
這裏沒有直接的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);
}
}
那麼,你在哪個部分掙扎,似乎是一個非常簡單的事情呢? – R0MANARMY
舉個更多的例子。爲什麼你合併'BC'和'100°F'?什麼規則支配這一點? –
@ J-16 SDiz這兩個只是例子,合併這個規則並不重要。我的疑問只是如何合併這兩個項目。可以換個話說。 –