【问题标题】:How can I merge two List<String> into a single List<String>?如何将两个 List<String> 合并为一个 List<String>?
【发布时间】:2014-04-26 20:54:52
【问题描述】:

我看到了一些关于同一件事的其他问题,但其中任何一个都解决了我的问题。可能是因为我不明白它的概念。

我有两个List&lt;String&gt;

List<String> PlatformInfo1 = new ArrayList
List<String> PlatformInfo2 = new ArrayList

那些列表内容来自我的数据库的一些信息:

PlatformInfo1= [{"Nnodes":"163"}]
PlatformInfo2= [{"Commnet":"Windows Machine"}]

为了与每个元素交互,我尝试将两个数组都包含在一个对象 List&lt;String&gt; 中:

List<String> PlatformInfoGI = new ArrayList<String>();
PlatformInfoGI.addAll(PlatformInfo1);
PlatformInfoGI.addAll(PlatformInfo2);

我得到的结果是:

Value of PlatformInfoGI: [{"Nnodes":"163"},{"Commnet":"Windows Machine"}]

可以做一些事情将那些List&lt;String&gt; 变成类似的东西:

 Value of PlatformInfoGI: [{"Nnodes":"163","Commnet":"Windows Machine"}]

NOTE 元素之间缺少大括号。

我想要的是一个List&lt;String&gt;,它只有一个元素和不同的属性(字符串)

【问题讨论】:

  • 一个包含一个元素和该元素不同属性的列表,听起来您需要创建一个自定义对象列表或两个字符串的映射。
  • 这段代码无法编译。

标签: java string arraylist merge


【解决方案1】:

使用 apache commons 集合'ListUtils.union(java.util.List list1, java.util.List list2)

返回一个新列表,其中包含附加到第一个列表的第二个列表 列表。 List.addAll(Collection) 操作用于追加两个 给定列表到一个新列表中。

【讨论】:

  • 我得到的结果与使用 addAll Value of PlatformInfoGI: [{"Nnodes":"163"},{"Commnet":"Windows Machine"}]
【解决方案2】:

稍作修改,

List PlatformInfo1 = new ArrayList();

List PlatformInfo2 = new ArrayList();

    PlatformInfo1.add("Nnodes");
    PlatformInfo1.add("163");

    PlatformInfo2.add("Commnet");
    PlatformInfo2.add("Windows Machine");

    List<String> PlatformInfoGI = new ArrayList<String>();
    PlatformInfoGI.addAll(PlatformInfo1);
    PlatformInfoGI.addAll(PlatformInfo2);

    System.out.println(PlatformInfoGI);

这会将结果打印为:[Nnodes, 163, Commnet, Windows Machine]

P.S:我可以知道您使用的是哪个 IDE 吗?

【讨论】:

    【解决方案3】:

    我认为没有理由将结果显示为: Value of PlatformInfoGI: [{"Nnodes":"163"},{"Commnet":"Windows Machine"}]

    对于这样的结果,它是一个包含 2 个对象的列表,而您已将列表定义为: **List<String>** PlatformInfoGI = new **ArrayList<String>**(); PlatformInfoGI.addAll(PlatformInfo1); PlatformInfoGI.addAll(PlatformInfo2);

    可以通过示例代码在您的控制台中向我显示结果吗?

    【讨论】:

    • 这是控制台中的结果:Value of PlatformInfoGI: [{"Nnodes":"163"},{"Commnet":"Windows Machine"}]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 2013-08-26
    • 1970-01-01
    • 2019-08-08
    • 2021-09-17
    • 2020-10-21
    • 1970-01-01
    相关资源
    最近更新 更多