繁体   English   中英

用Java中的多个元素替换Collection的元素的最佳方法

[英]Best way to replace an element of a Collection with multiple elements in Java

我有一个字符串值集合。 如果值之一是“ *”,我想用另外3个值代替,例如“ X”,“ Y”和“ Z”。

换句话说,我想将[“ A”,“ B”,“ *”,“ C”]转换为[“ A”,“ B”,“ X”,“ Y”,“ Z”,“ C”]。 顺序无关紧要,因此只需删除其中一个并添加其他内容即可。 使用该示例,可以想到以下这些方法:

Collection<String> additionalValues = Arrays.asList("X","Y","Z"); // or set or whatever
if (attributes.contains("*")) {
    attributes.remove("*");
    attributes.addAll(additionalValues);
}

要么

attributes.stream()
          .flatMap(val -> "*".equals(val) ? additionalValues.stream() : Stream.of(val))
          .collect(Collectors.toList());

最有效的方法是什么? 再说一次,顺序并不重要,理想情况下,我想删除重复项(因此可能是流中的distinct()或HashSet?)。

我会以与您的第一种方式非常相似的方式进行操作:

if (attributes.remove("*")) {
    attributes.addAll(additionalValues);
}

您不需要单独的removecontains 对正确实现的collection的调用:

[ Collection.remove(Object) ]从此集合中移除指定元素的单个实例( 如果存在) (可选操作)。 更正式地讲,如果此集合包含一个或多个这样的元素,则删除元素(e == null?e == null:o.equals(e))。 如果此集合包含指定的元素 (或者等效地,如果此集合由于调用而更改),则返回true

我认为第二个更好。 Arrays.asList("X","Y","Z")检索ArrayList即数组。 替换其中的值不是很好。

在一般情况下,如果您想修改一个集合(例如,将*替换为XYZ ),请以某种方式创建集合。

如果要修改集合本身,请查看LinkedList

使用流:

public static List<String> replace(Collection<String> attributes, String value, Collection<String> additionalValues) {
    return attributes.stream()
                     .map(val -> value.equals(val) ? additionalValues.stream() : Stream.of(val))
                     .flatMap(Function.identity())
                     .collect(Collectors.toList());
}

不使用流

public static List<String> replace(Collection<String> attributes, String value, Collection<String> additionalValues) {
    List<String> res = new LinkedList<>();

    for (String attribute : attributes) {
        if (value.equals(attribute))
            res.addAll(additionalValues);
        else
            res.add(attribute);
    }

    return res;
}

演示:

List<String> attributes = Arrays.asList("A", "B", "*", "C");
List<String> res = replace(attributes, "*", Arrays.asList("X", "Y", "Z"));  // ["A", "B", "X", "Y", "Z", "C"]

为了获得最佳性能,并在正确的位置插入替换值,请使用indexOf(o)remove(index)addAll(index, c)

演示版

List<String> attributes = new ArrayList<>(Arrays.asList("A", "B", "*", "C"));
Collection<String> additionalValues = Arrays.asList("X","Y","Z");

int idx = attributes.indexOf("*");
if (idx != -1) {
    attributes.remove(idx);
    attributes.addAll(idx, additionalValues);
}

System.out.println(attributes);

输出量

[A, B, X, Y, Z, C]

如果顺序无关紧要,请使用remove(o)的返回值:

if (attributes.remove("*"))
    attributes.addAll(additionalValues);

输出量

[A, B, C, X, Y, Z]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM