1
int arr[] = new int[10]; for(int i=0;i<10;i++){ arr[i]=s.nextInt(); } Arrays.sort(arr); System.out.println(" "+Arrays.toString(arr)); 

my input is :

98 7 6 5 4 32 14 5 1 7

my output is :

[1, 4, 5, 5, 6, 7, 7, 14, 32, 98]

but i want to print my output as sorted number only but not with [ ] and commas what would be the required solution

2
  • 1
    after read the input: System.out.println(Stream.of(arr).sorted( ).map( String::valueOf ).collect( Collectors.joining( " " ) )); Commented Aug 15, 2018 at 4:31
  • Morteza's answer is a better performance solution Commented Aug 13, 2021 at 5:57

3 Answers 3

4

Just loop over the array, and print each number.

for (int i: arr) { System.out.print(i); System.out.print(" "); } System.out.println(); 
Sign up to request clarification or add additional context in comments.

3 Comments

..this one worked perfectly..without scratching my mind..but why we are printing index value since we have to print element of that index will you please explain
In a for-each-loop the i is not the index, but the element of the collection you are iterating over. This is different from for (int i=0; i<10; i++)
This has a trailing space which might not be desirable.
4

Use replaceAll to replace [ and ] with empty string:

System.out.println(" " + Arrays.toString(arr).replaceAll("[\\[|\\]]", "")); 

Comments

3

One solution is to iterate over the array and print the desired string. Another solution is just using substring as following:

String result = Arrays.toString(arr); System.out.println(" "+result.substring(1, result.length()-1)); 

By iterating also you can get this result as following:

for (int i=0;i<arr.length;i++){ System.out.print(arr[i] + " "); } 

Or using regex, you can replace first and last characters as following:

System.out.println(" " + Arrays.toString(arr).replaceAll("^.|.$", "")); 

You can also use StringUtils(commons-lang) which is null safe:

StringUtils.substringBetween(Arrays.toString(arr), "[", "]"); 

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.