Showing posts with label java - Arrays class. Show all posts
Showing posts with label java - Arrays class. Show all posts

Tuesday, November 28, 2017

JAVA - How to make custom array sorting

In some situation is necessary make own custom sorting function. For this reason use class java.util.Comparator. In this class instance you must override compare() function.
/* -- array - one item with small first letter */

String[] array = { "one", "Two", "Three", "Four", "Fight" };

/* -- regular sorting */

Arrays.sort( array );

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

/* -- sorting with own sorting function (ignoring letter size) */

Arrays.sort( array, new Comparator() {
  @Override
  public int compare( String s1, String s2 ) {
    return( s1.compareToIgnoreCase( s2 ) );
  }    
});

System.out.println( Arrays.toString( array ) );
The output is:
[Fight, Four, Three, Two, one]
[Fight, Four, one, Three, Two]
First output row is regular sorting. Second row is our custom sorting function that ignores letter case size.

JAVA - How to sort array elements in descending order

For sorting array elements use class java.util.Arrays. This class contains static methods for work with arrays.
String[] array = { "One", "Two", "Three", "Four", "Fight" };

Arrays.sort( array, Collections.reverseOrder() );

System.out.println( Arrays.toString( array ) );
For descending sorting use comparator Collections.reverseOrder().

Output is:
[Two, Three, One, Four, Fight]

Monday, November 27, 2017

JAVA - How to create multidimensional array

/* -- declaration and initialization of multidimensional 2D array */

int[][] doubleArray = 
{
  { 1, 3, 5 },
  { 2, 4, 6 }
};

/* -- go through multidimensional array (by rows) */

for ( int iRow = 0; iRow < doubleArray.length; iRow++ ) {   
  int[] iArray = doubleArray[ iRow ];          

  System.out.println( Arrays.toString( iArray ) );     
} 
Output:
[1, 3, 5]
[2, 4, 6]

Thursday, November 23, 2017

JAVA - How to quickly list (all) array elements

For quickly list array elements use class java.util.Arrays. This class contains static methods for work with arrays.
String[] array = new String[3];

array[0] = "One";
array[1] = "Two";
array[2] = "Three";

System.out.println( Arrays.toString( array ) );
The output is:
[One, Two, Three]

Wednesday, November 22, 2017

JAVA - How to sort array elements

For sorting array elements use class java.util.Arrays. This class contains static methods for working with arrays.
String[] array = { "One", "Two", "Three", "Four", "Fight" };

Arrays.sort( array );

System.out.println( Arrays.toString( array ) );
The output is:
[Fight, Four, One, Three, Two] 
NOTE: This is the most simplest variant of array sorting.