0

All I keep seeing is sorting of string / integer array list. What I'm looking for how is how to sort a number. Example, I have a 190 format, I want it to sort to 019. Any help is appreciated, thanks!

6
  • There may be a specific way of easily doing it, but you could always convert it to a String, sort it, then convert it back to an Int too and just throw that into a method that you call if you need to do it a lot. Also I don't think it is possible to store 019 as an int, it will be changed to 19. Commented Jun 6, 2019 at 11:54
  • You want to transform a number X into a different number Y, and then sort on the basis of Y? What is the general transformation that takes 190 to 019? What would the transformation of 123 look like? 312? 012? What does 19 transform to? 190? Commented Jun 6, 2019 at 11:56
  • @another-dave I just need to sort it in an ascending order. 742 should be 247 Commented Jun 6, 2019 at 11:58
  • >*Also I don't think it is possible to store 019 as an int, it will be changed to 19*. There is no distinction to be made. There are "both" the bit pattern 00000000 00000000 00000000 00010011 in memory. How they get displayed as decimal digits is up to you. Commented Jun 6, 2019 at 11:59
  • Having 019 was just an example. I just need to sort every string/number in an ascending order. Commented Jun 6, 2019 at 12:00

7 Answers 7

2

You can convert your int into a String and split in a array, next just sort the stream and join in a single String.

String[] number = "190".split("");

String list =  Stream.of(number).sorted().collect(Collectors.joining());

System.out.println(list); //Output: 019
Sign up to request clarification or add additional context in comments.

Comments

2

You can do it like this:

   package test;

    public class Test2 {

        public static void main(String[] args) throws Exception {
            String number = "153004";
            String sorted = sortStringNumbers(number);
            System.out.println(sorted);
        }

        private static String sortStringNumbers(String numbersString) {
            return numbersString.chars().mapToObj(c -> Character.toString((char)c)).sorted().collect(Collectors.joining());
        }

    }

Output:

001345

Comments

2

You can create a List with the digits of your number and sort this List.

List<Integer> nums=new ArrayList<>();
for(int num=toSort;num>0;num/=10){
    nums.add(num%10);
}
Collections.sort(nums);
String result="";//If you want the result to be a integer (e.g. 190 will convert into 19 and not 019), change this to int result=0;
for(Integer num:nums){
    result+=num.intValue();
    /*int:
    result+=num.intValue();
    result×=10;*/
}

1 Comment

Hi there, I tried changing the string result ="" to int and it shows the result of 10
1

From my understanding of your question you are trying to sort the digits in an int. This can be done by converting to a CharArray, sorting, then returning the result. Note that this will fail for negative numbers.

fun sortInt(int: Int): Int =
        int.toString()
                .toCharArray()
                .sorted()
                .joinToString("")
                .toInt()

EDIT: Now this will work for 0 digit also.

fun sortInt(int: Int): String =
        int.toString()
                .toCharArray()
                .sorted()
                .joinToString("")

Comments

1

Plenty of ways to achieve this. Here's one:

final String sorted = "190".chars()
    .sorted()
    .mapToObj(c -> Character.valueOf((char)c).toString())
    .collect(Collectors.joining())

and

final String sorted = "190".chars()
    .sorted()
    .collect(StringBuilder::new, (sb, c) -> sb.append((char) c), StringBuilder::append)
    .toString();

And, as a single-liner that will (I think) work in Java 7 (not production code but fun to do)...

final String sorted = Arrays.toString(new PriorityQueue<>(Arrays.asList("190".split("")))
    .toArray(new String[0]))
    .replaceAll("\\W+", "");

4 Comments

Your first answer works for me. Question, what does setting language level to 8 - Lambdas do?
It means you can access Java 8 features, like lambdas. Some features are supported on older versions of Android whilst some features are not.
Does using it affect functionalities of my old code?
Nope, it just adds new features
0

Updates @dan1st answer, to get desired result:

        List<Integer> nums = new ArrayList<>();
        String total = "";
        for( int num = 190; num>0; num/=10 ){
            nums.add(num%10);
        }
        Collections.sort(nums);
        for (Integer x : nums) {
            total += x.toString();
        }
        Integer finalResult = Integer.parseInt(total);
        Log.i(TAG,"=== finalResult  "+ finalResult);
        O/P : 019

Comments

0

you should be care if you use this :

sortInt(190)
fun sortInt(int: Int): Int =
        int.toString()
                .toCharArray()
                .sorted()
                .joinToString("")
                .toInt()

the output will be 19 and not 019

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.