我正在尝试组合多个字符串列表。
假设我有两个(可能更多)相同大小的列表:
List<String> list1 = Arrays.asList("1One","1Two","1Three");
List<String> list2 = Arrays.asList("2One","2Two","2Three");
我想组合相应索引的值并将它们放入一个新列表中:
List3 = new {"1One2One", "1Two2Two", "1Three2Three"};
目前我有一个包含2个对象的列表,每个对象都包含我想要组合其中元素的列表。
所以我想将对象1列表中的元素1与对象2列表中的元素1组合。
这就是我的尝试:
public void generateFileList(List<Object> cl){
int count = 0;
String temp = "";
for(int i = 0; i < cl.size(); i++){
for (int x = 0; x < cl.get(i).getItemList().size(); x++) {
if (count == x){
temp += cl.get(i).getListItem(x);
break;
}
}
count++;
textList.add(temp);
}
}
public void test(){
for(String s : textList){
System.out.println("List Element - " + s);
}
System.out.println(textList.size());
}
打印出来:
List Element - 1One
List Element - 1One1Three
我在这里做错了什么?
答案 0 :(得分:1)
如果列表具有相同的大小,只需要从0到列表大小的for循环,并在新列表中添加两个列表中相同位置的元素的串联,例如(int i = 0; i&lt; list1.size(); i ++){resullist.add(list1.get(i)+ list2.get(i))}
答案 1 :(得分:1)
首先,您已经编译的代码。它应该是:
List<String> list1 = Arrays.asList("1One","1Two","1Three");
List<String> list2 = Arrays.asList("2One","2Two","2Three");
接下来,最好使用Iterator
而不是按索引访问List
:
public List<String> concat(final List<String> list1, final List<String> list2) {
final Iterator<String> i1 = list1.iterator();
final Iterator<String> i2 = list2.iterator();
final List<String> combined = new ArrayList<>();
while (i1.hasNext() && i2.hasNext()) {
combined.add(i1.next() + i2.next());
}
return combined;
}
对于任意数量的List
:
public List<String> concat(final List<String>... lists) {
final List<Iterator<String>> it = new LinkedList<>();
for (List<String> l : lists) {
it.add(l.iterator());
}
final List<String> combined = new ArrayList<>();
outer:
while (true) {
final StringBuilder sb = new StringBuilder();
for (final Iterator<String> i : it) {
if (!i.hasNext()) {
break outer;
}
sb.append(i.next());
}
combined.add(sb.toString());
}
for (final Iterator<String> i : it) {
if (i.hasNext()) {
throw new IllegalArgumentException("Lists not the same length.");
}
}
return combined;
}
答案 2 :(得分:0)
假设2个列表大小相同:
List<String> list1 = new {"1One","1Two","1Three"};
List<String> list2 = new {"2One","2Two","2Three"};
List<String> list3 = new ArrayList<>();
for (int i = 0; i < list1.size(); i++) {
list3.add(list1.get(i) + list2.get(i));
}