简体   繁体   中英

Convert Set<Integer> to Set<String> in Java

有没有一种简单的方法可以将Set<Integer>转换为Set<String>而不遍历整个集合?

No. The best way is a loop.

HashSet<String> strs = new HashSet<String>(ints.size());
for(Integer integer : ints) {
  strs.add(integer.toString());
}

Something simple and relatively quick that is straightforward and expressive is probably best.

(Update:) In Java 8, the same thing can be done with a lambda expression if you'd like to hide the loop.

HashSet<String> strs = new HashSet<>(ints.size());
ints.forEach(i -> strs.add(i.toString()));

or, using Streams,

Set<String> strs = ints.stream().map(Integer::toString).collect(toSet());

use Java8 stream map and collect abilities:

 Set< String >  stringSet = 
   intSet.stream().map(e -> String.valueOf(e)).collect(Collectors.toSet());

不。您必须格式化每个整数并将其添加到您的字符串集中。

如果您真的不想遍历整个集合,则可以使用装饰器

You could use Commons Collections' TransformedSet or Guava's Collections2.transform(...)

In both cases, your functor would presumably simply call the Integer's toString().

Using Eclipse Collections with Java 8:

Set<String> strings = IntSets.mutable.with(1, 2, 3).collect(String::valueOf);

This doesn't require boxing the int values and Integer, but you can do that as well if required:

Set<String> strings = Sets.mutable.with(1, 2, 3).collect(String::valueOf);

Sets.mutable.with(1, 2, 3) will return a MutableSet<Integer> , unlike IntSets.mutable.with(1, 2, 3) which will return a MutableIntSet .

Note: I am a committer for Eclipse Collections.

AFAIK, you have to iterate through the collection; especially when there is a conversion involved that isn't natural. ie if you were trying to convert from Set-Timestamp- to Set-Date-; you could achieve that using some combination of Java Generics (since Timestamp can be cast to Date). But since Integer can't be cast to String, you will need to iterate.

You could implement Set<String> yourself and redirect all calls to the original set taking care of the necessary conversions only when needed. Depending on how the set is used that might perform significantly better or significantly worse.

private static <T> Set<T> toSet(Set<?> set) {
    Set<T> setOfType = new HashSet<>(set.size());
    set.forEach(ele -> {
        setOfType.add((T) ele);
    });
    return setOfType;
 }

Java 7 + Guava(大概没有办法切换到 Java 8)。

new HashSet<>(Collections2.transform(<your set of Integers>, Functions.toStringFunction()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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