gpt4 book ai didi

java - 如何在 Java 中组合两个具有相同数量元素的列表?

转载 作者:行者123 更新时间:2023-12-01 06:33:22 26 4
gpt4 key购买 nike

如何在 Java 中组合两个列表?到目前为止的输出是:

Firstname1
Firstname2
Firstname3
Lastname1
Lastname2
Lastname3
[[Firstname1, Firstname2, Firstname3], [Lastname1, Lastname2, Lastname3]]

我希望输出是:

[名字1 姓氏1,名字2 姓氏2,名字3 姓氏3}

import java.util.Arrays;
import java.util.List;
import java.util.Iterator;
import java.util.HashSet;

public class Main {

public static void main(String[] args) {
List<String> peoplFname = Arrays.asList("Firstname1", "Firstname2", "Firstname3");
List<String> peoplLname = Arrays.asList("Lastname1", "Lastname2", "Lastname3");
Iterator<String> iterator = peoplFname.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}

Iterator<String> iteratorx = peoplLname.iterator();
while(iteratorx.hasNext()) {
System.out.println(iteratorx.next());
}

HashSet peopleFullName = new HashSet();

peopleFullName.add(peoplFname);
peopleFullName.add(peoplLname);

System.out.println(peopleFullName.toString());
}
}

最佳答案

使用addAll而不是 add,以便将列表中的所有元素添加到您的集合中。

将代码更改为:

peopleFullName.addAll(peoplFname);
peopleFullName.addAll(peoplLname);

更新:

根据更新的问题,您似乎想要合并两个列表中的相应元素。你走在正确的轨道上。您只需迭代两个列表,将名字与姓氏连接起来,然后将其添加到结果列表中:

List<String> peoplFname = Arrays.asList("Firstname1", "Firstname2", "Firstname3");
List<String> peoplLname = Arrays.asList("Lastname1", "Lastname2", "Lastname3");

Iterator<String> iterator = peoplFname.iterator();
Iterator<String> iteratorx = peoplLname.iterator();

List<String> peopleFullName = new ArrayList<String>();

while(iterator.hasNext() && iteratorx.hasNext()) {
String fullName = iterator.next() + " " + iteratorx.next();
peopleFullName.add(fullName);
}

System.out.println(peopleFullName);

关于java - 如何在 Java 中组合两个具有相同数量元素的列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8882895/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com