繁体   English   中英

将int数组转换为String数组

[英]Converting an int array to a String array

所以我有这个整数的“清单”。 它可以是Vectorint[]List<Integer>等等。

我的目标是对int进行排序并最终得到一个String[] int数组如何在空中开始。

例如:开始于: {5,1,2,11,3}结束时: String[] = {"1","2","3","5","11"}

反正没有for循环吗? 我现在有一个for循环用于收集整数。 我宁愿跳过另一个for循环。

int[] nums = {5,1,2,11,3}; //List or Vector
Arrays.sort(nums); //Collections.sort() for List,Vector
String a=Arrays.toString(nums); //toString the List or Vector
String ar[]=a.substring(1,a.length()-1).split(", ");
System.out.println(Arrays.toString(ar));

更新:

更短的版本:

int[] nums = {-5,1,2,11,3};
Arrays.sort(nums);
String[] a=Arrays.toString(nums).split("[\\[\\]]")[1].split(", "); 
System.out.println(Arrays.toString(a));  

使用Java 8中提供的Stream 。要获取具有整数“list”的Stream实例:

  • 对于int[]
    • IntStream intStream = Arrays.Stream(nums); 要么
    • Stream<Integer> intStream = Arrays.Stream(nums).boxed(); 如果你需要与底层相同的课程。
  • 对于具有Collection<Integer>接口的任何类(例如Vector<Integer>List<Integer>
    • Stream<Integer> intStream = nums.stream();

最后,获取String[]

String[] answer = intStream.sorted().mapToObj(String::valueOf).toArray(String[]::new);

我可以使用while循环吗?

@Test
public void test() {
    int[] nums = {5,1,2,11,3};

    Arrays.sort(nums);

    String[] stringNums = new String[nums.length];
    int i = 0;
    while (i < nums.length) {
        stringNums[i] = String.valueOf(nums[i++]);
    }

    Assert.assertArrayEquals(new String[]{"1","2","3","5","11"}, stringNums);
}

使用JUnit断言。

对不起,我很轻浮。 但是说你不能使用for循环是愚蠢的 - 你必须以某种方式迭代列表。 如果您打算调用库方法为您排序(cf Collections.sort() ) - 那将以某种方式循环元素。

使用Guava的简单解决方案:

public List<String> toSortedStrings(List<Integer> ints) {
  Collections.sort(ints);
  return Lists.newArrayList(Iterables.transform(ints, 
      Functions.toStringFunction()));
}

显然,这个解决方案(与其他任何解决方案一样)将在内部使用循环,但它会从您必须阅读的代码中获取它。 您还可以通过将Ordering.natural().sortedCopy(ints)的结果传递给transform而不是先使用Collections.sort来避免更改ints的顺序。 此外,如果您不需要能够将新元素添加到结果列表中,则Lists.newArrayList部分。

该方法体的缩短版本,带有静态导入:

return transform(Ordering.natural().sortedCopy(ints), toStringFunction());

如果你使用TreeSet,我有一个(长)单行(假设items是TreeSet):

final String[] arr =
    items.toString() // string representation
        .replaceAll("\\D+", " ") // replace all non digits with spaces
        .trim() // trim ends
        .split(" "); // split by spaces

测试代码:

Set<Integer> items = new TreeSet<Integer>(Arrays.asList(5, 1, 2, 11, 3));

// insert above code here

System.out.println(Arrays.toString(arr));

输出:

[1, 2, 3, 5, 11]

编辑:

好的,这是一个直接与int数组一起使用的不同版本。 但不幸的是,这不是一个单行。 但是,它确实保留了重复数据,而且可能更快

再次编辑:

根据要求支持错误修复和负数:

再次编辑 :只有一个正则表达式通过而没有修剪

    final int[] in = { 5, 1, 2, 11, 3, 2, -5 }; // with duplicate
    Arrays.sort(in);
    final String[] out =
        Arrays.toString(in)
            .replaceAll("(?:\\[?)([-\\d]+)(?:\\]?)", "$1") // just remove [ and ]
            .split("\\s*,\\s*"); // split by comma

    System.out.println(Arrays.toString(out));

输出:

[-5, 1, 2, 2, 3, 5, 11]

或完全没有正则表达式 (除了split()),但添加了一个步骤:

final int[] in = { 5, 1, 2, 11, 3, 2, -5 }; // with duplicate
Arrays.sort(in);
final String stringRep = Arrays.toString(in);
final String[] out =
    stringRep.substring(1, stringRep.length() - 1).split("\\s*,\\s*");

System.out.println(Arrays.toString(out));

输出:

[-5, 1, 2, 2, 3, 5, 11]

更新:从我的最后两个解决方案剥离空白,希望你现在开心:-)

我宁愿跳过另一个for循环。

那太傻了。 进行代码练习是一种愚蠢的愿望和愚蠢的基础。 如果你能更好地表达你希望你的代码具有的品质,那么我们就有了一些可以讨论的东西 - 它应该易于阅读,比如说,性能,可测试性或健壮性。 但“我宁愿跳过它”只是没有给我们任何有用的东西。

使用Functional Java

import fj.data.List;
import static fj.data.List.*;
import static fj.pre.Show.*;
.
.
.
final List<Integer> xs = list(5,1,2,11,3);
final List<String> ys = xs.sort(Ord.intOrd).map(
  new F<Integer, String>() {
    @Override public String f(final Integer i) {
       return String.valueOf(i);
    }
  }
);
listShow(stringShow).println(ys);

这样的事情怎么样:

List<String> stringList = new ArrayList<String>();
List<Integer> list = new ArrayList<Integer>(Arrays.asList(5,1,2,11,3));
Collections.sort(list);
Iterator<Integer> iterator = list.iterator();
while(iterator.hasNext()) {
  stringList.add(iterator.next().toString());
}
System.out.println(stringList);

使用Eclipse集合 MutableIntList

String[] result = IntLists.mutable.with(5, 1, 2, 11, 3)
        .sortThis()
        .collect(Integer::toString)
        .toArray(new String[]{});

Assert.assertArrayEquals(
        new String[]{"1", "2", "3", "5", "11"}, result);

或者为可能的效率交易一些可读性:

MutableIntList intList = IntLists.mutable.with(5, 1, 2, 11, 3).sortThis();
String[] result = intList.injectIntoWithIndex(
        new String[intList.size()], 
        (r, each, index) -> {
            r[index] = Integer.toString(each);
            return r;
        });

Assert.assertArrayEquals(
        new String[]{"1", "2", "3", "5", "11"}, result);

注意:我是Eclipse Collections的提交者

为什么不简单地将这些值转换为原始for循环中的String,创建一个String数组而不是一个int数组? 假设您从起始点收集初始整数并在每个for循环迭代中添加它,以下是创建String数组而不是int数组的简单方法。 如果你需要int和String数组都有相同的值,那么在同一个for循环中创建它们并完成它。

yourInt = someNumber;

for (int a = 0; a < aLimit; a ++) {

String stringName = String.valueOf(yourInt);
StringArrayName[a] = stringName;
yourInt ++;

}

或者,如果您需要两者:

yourInt = someNumber;

for (int a = 0; a < aLimit; a ++) {

String stringName = String.valueOf(yourInt);
StringArrayName[a] = stringName;
intArrayName[a] = yourInt;
yourInt ++;

}

我同意其他人。 For循环很容易构造,几乎不需要运行开销,并且在阅读代码时很容易理解。 优雅简约!

您可以使用Collections.sort()然后遍历列表并收集String.valueOf()每个元素。

http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List%29

对于Vector,您首先会得到一个List with Collections.list(Enumeration e)

对于数组,您将使用Arrays.sort()而不是Collections.sort()

http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort%28int%5b%5d%29

Java 8方式,根本没有循环:

 // Given
int[] array         = {-5, 8, 3, 10, 25};
// When
String[] actual = Arrays.stream(array)
        .sorted()
        .mapToObj(String::valueOf)
        .toArray(String[]::new);
// Then
String[] expected = {"-5", "3", "8", "10", "25"};

assertArrayEquals(expected, actual);

我们可以使用正则表达式解决此问题,如下所示:

int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
String str = new String(Arrays.toString(intArray));
String stripNoneDigits= str.replaceAll("[^\\d]", "");
String[] stringArray = stripNoneDigits.split("");

Arrays.sort(NUMS); var stringArray =(nums.toString())。split(',')。map(String);

暂无
暂无

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

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