Converting an int array to a String array

前端 未结 14 1345
予麋鹿
予麋鹿 2020-12-01 14:21

So I have this \"list\" of ints. It could be a Vector, int[], List, whatever.

My goal though is to sort the

相关标签:
14条回答
  • 2020-12-01 14:56

    Use a Stream which is available from Java 8. To get a Stream instance with "list" of ints:

    • For int[]
      • IntStream intStream = Arrays.Stream(nums); or
      • Stream<Integer> intStream = Arrays.Stream(nums).boxed(); if you need the same class as bottom one.
    • For any classes with Collection<Integer> interface (ex. Vector<Integer>, List<Integer>)
      • Stream<Integer> intStream = nums.stream();

    Finally, to get a String[]:

    String[] answer = intStream.sorted().mapToObj(String::valueOf).toArray(String[]::new);
    
    0 讨论(0)
  • 2020-12-01 14:57

    If you use a TreeSet, I have a (longish) one-liner for you (assuming items is the TreeSet):

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

    Test code:

    Set<Integer> items = new TreeSet<Integer>(Arrays.asList(5, 1, 2, 11, 3));
    
    // insert above code here
    
    System.out.println(Arrays.toString(arr));
    

    Output:

    [1, 2, 3, 5, 11]
    

    EDIT:

    OK, here is a different version that works with the int array directly. But unfortunately it's not a one-liner. However, it does keep duplicates and it's probably faster

    EDIT again:

    Bug fixed and negative numbers supported, as requested:

    EDIT once more: only one regex pass and no trim

        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));
    

    Output:

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

    Or completely without regex (apart from split()), but with one more step added:

    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));
    

    Output:

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

    Update: stripped whitespace from my last two solutions, hope you're happy now :-)

    0 讨论(0)
提交回复
热议问题