【问题标题】:Create a Java for loop to concatenate 2 sets of strings创建一个 Java for 循环以连接 2 组字符串
【发布时间】:2016-05-21 11:33:24
【问题描述】:

我有 Map<String, String> prefixes

List<String> annotationProperties

我正在尝试获取字符串输出 prefix: annotationProperty 对于每个条目(它们是按顺序输入的)。

有没有我可以用来连接这些的 for 循环?我需要将条目作为 List<String> 返回以在 XML 输出中使用。

谢谢!

【问题讨论】:

  • 可以提供样品吗?
  • 不完全确定你在问什么;您想获取annotationProperties 中的每个项目并创建一个字符串列表,其中包含prefixes 中的项目和该键的值?
  • 您能否提供一个输入和预期输出的最小示例?
  • 您是否使用字符串连接生成 XML?
  • 我在 Java 8 中,我正在使用 StringBuilder。我只想将前缀与它的注释属性连接起来。因此,输入类似于前缀列表 {"owl","rdf","xds"}(实际上是一个 Map)和注释属性列表 {"w3.org/2002/07/owl#","http://www.w3.org/1999/02/…"}。我想要的输出是 {"owl : w3.org/2002/07/owl#", etc...}

标签: java string list for-loop dictionary


【解决方案1】:

我假设annotationPropertiesprefix 映射的键。如果是这种情况,那么在 Java 8 中你可以这样做:

List<String> output = annotationProperties.stream()
        .map(prop -> String.format("%s: %s",  prefix.get(prop), prop))
        .collect(Collectors.toList());

调用stream,以便您可以使用流函数,例如mapcollect

调用mapannotationProperties 中的字符串转换为您想要的输出

并调用collect 将流转换回列表


如果你想使用 for 循环,你也可以这样做:

// The end size is known, so initialize the capacity.
List<String> output = new ArrayList<>(annotationProperties.size());
for (String prop : annotationProperties){
    output.add(String.format("%s: %s",  prefix.get(prop), prop));
}

可以设置一个等于.collect(Collectors.toList());的变量吗?

我们已经有了!在这两种情况下,我们都创建了一个变量output,它是一个格式化为prefix: property 的字符串列表。如果你想使用这个列表,那么你可以像这样循环它:

for (String mystring : output) {
    // do xml creation with mystring
}

或者像这样:

for (int i = 0; i < output.size(); i++){
    String mystring = output.get(i);
    // do xml creation with mystring
}

或者像这样:

output.stream().forEach(mystring -> {
    // do xml creation with mystring
});

【讨论】:

  • 谢谢,是的,我应该更具体地了解 annotationProperties。这正是我想要的!
  • 还有一个问题 - 如果我想在 for 循环中使用这个输出来添加到我的 XML 中,我将如何调用结果?可以设置一个等于 .collect(Collectors.toList()); 的变量吗? ?
  • 非常感谢。不幸的是,这是空的......在这里尝试了一些不同的东西,它似乎不喜欢它。
猜你喜欢
  • 1970-01-01
  • 2017-07-10
  • 2015-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多