假设我有以下列表:
A | B | C | D
或the | temperature | is | 100 | °F | today
我想将两个属性合并为一个,如下所示:
A | BC | D
或the | temperature | is | 100°F | today
我怎样才能做到这一点?如果需要,可以更改集合。
答案 0 :(得分:4)
如果你想要做的是拿一个元素及其后继并合并它们,这应该有效:
String i = list.get(iIndex);
String j = list.get(iIndex + 1);
i= i.concat(j);
list.set(iIndex,i);
list.remove(iIndex + 1);
答案 1 :(得分: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;
}
}
答案 2 :(得分: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);
}
}