JavaRush /Java Blog /Random EN /Coffee break #136. Sort an array in ascending or descendi...

Coffee break #136. Sort an array in ascending or descending order with Arrays.sort(). What is the difference between List and Set interfaces?

Published in the Random EN group

Sort an array in ascending or descending order with Arrays.sort()

Source: FreeCodeCamp Thanks to this post, you will learn how to sort an array in ascending or descending order in Java. Coffee break #136.  Sort an array in ascending or descending order with Arrays.sort().  What is the difference between List and Set interfaces?  - 1In Java, we use arrays to store a set of variables (with the same data type) in a single variable. But sometimes the values ​​stored in an array appear randomly. Thanks to the Arrays class in Java, we have several ways to manage arrays, including sorting them. One of the methods we'll be using from the Arrays class is the sort() method , which sorts an array in ascending order. To sort an array in descending order, use the reverseOrder() method of the Collections class in Java.

How to sort an array in ascending order in Java using Arrays.sort()

Here is an example of how we can use the sort() method to sort an array in ascending order.
import java.util.Arrays;

class ArraySort {
    public static void main(String[] args) {
        int[] arr = { 5, 2, 1, 8, 10 };
        Arrays.sort(arr);

        for (int values : arr) {
            System.out.print(values + ", ");
            // 1, 2, 5, 8, 10,
        }
    }
}
The first thing we did in the example above is to import the Arrays class : import java.util.Arrays; . This way we have access to all the methods of the Arrays class . We then created an array with numbers in random order: int[] arr = { 5, 2, 1, 8, 10 }; . To sort this array in ascending order, we passed the array as a parameter to the sort() method : Arrays.sort(arr); . Note that the Arrays class is written first before accessing the sort() method using dot notation. Finally, we created a loop and printed the array to the console. The result is a sorted array: 1, 2, 5, 8, 10. Now let's talk about sorting an array in descending order.

How to sort an array in descending order in Java using Collections.reverseOrder()

To sort an array in descending order, you should use reverseOrder() , which can be accessed from the Collections class . We will still use Arrays.sort(); , but in this example it will take two parameters - an array to sort and Collections.reverseOrder() .
import java.util.Arrays;
import java.util.Collections;

class ArraySort {
    public static void main(String[] args) {
        Integer[] arr = { 5, 2, 1, 8, 10 };
        Arrays.sort(arr, Collections.reverseOrder());

        for (int values : arr) {
            System.out.print(values + ", ");
            // 10, 8, 5, 2, 1,
        }
    }
}
We first imported the Arrays and Collections classes because we will be using the methods provided by these classes. We then created an array of numbers in random order: Integer[] arr = { 5, 2, 1, 8, 10 }; . As you can see, we used Integer[] instead of int[] as in the previous example. Otherwise, an error will occur. To sort an array in descending order, we did this: Arrays.sort(arr, Collections.reverseOrder()); . The first parameter is an array arr , which will be sorted in ascending order. The second parameter is Collections.reverseOrder()- then reorder the sorted array so that it is in descending order. When looping through and printing, the array will look like this: 10, 8, 5, 2, 1 .

Conclusion

In this article, we discussed sorting arrays in Java - how they can be sorted in ascending or descending order. To do this, we can use the sort() method , which can be accessed from the Arrays class . The sort() method takes an array to sort as a parameter. To sort an array in descending order, we used the reverseOrder() method provided by the Collections class. It is passed as the second parameter to the sort() method so that the sorted array can be reordered in descending order.

Java Collection. What is the difference between List and Set interfaces?

Source: Rrtutors List and Set are Java interfaces to extend the Collection interface . In this post, we'll look at the key differences between the two, as well as how they can be applied.

Differences between Set and List interfaces in Java

Let's define the key differences between the List and Set interfaces based on the following key parameters:

Implementation

List implement ArrayLists while HashSet implement Set .

Indexing

You can use a ListIterator to move forward or backward through a List , but not through a Set . Instead, use an Iterator (which works on both List and Set ).

Order

The Set interface does not support any particular given order. The collection of the Set type is already sorted according to its own rule and cannot be sorted just like that. List is an ordered list. Objects are stored in the order they were added to the list. List elements are accessed by index.

Null object

List have no restrictions and support the addition of null values ​​(Null values), while Set allows no more than one null value.

duplicates

Lists can contain duplicates, but Sets can't. Set does not allow duplicate elements, since all of its elements must be unique. If you insert a duplicate element into a Set , the existing value will be overwritten.

When should you use List and Set?

Set is the best choice when you just need to store unique values ​​because that's what it's designed for. But if you want to preserve the insertion order despite duplication, List is your best bet .

Set Example

import java.util.ArrayList;

import java.util.LinkedList;

import java.util.List;

public class ListExample {

            public static void main(String[] args) {

                        List<String> al = new ArrayList<String>();

                          al.add("Rohit");

                          al.add("Panjab");

                          al.add("Kamir");

                          System.out.println("My ArrayList Items: ");

                          System.out.print(al);

                          List<String> ll = new LinkedList<String>();

                          ll.add("Shobit");

                          ll.add("Raul");

                          ll.add("Ketel");

                          System.out.println("\n My LinkedList Items: ");

                          System.out.print(ll);

            }

}

List Example

import java.util.HashSet;

import java.util.Set;

import java.util.TreeSet;

public class SetExample {

            public static void main(String[] args) {

                          int myList[] = {60, 70, 80, 40 };

                            Set<Integer> dispSet = new HashSet<Integer>();

                            try{

                              for(int i = 0; i<4; i++){

                                dispSet.add(myList[i]);

                              }

                              System.out.println(dispSet);

                              TreeSet<Integer> treeset = new TreeSet<Integer>(dispSet);

                              System.out.println("Sorting in Asceding order:");

                              System.out.println(treeset);

                            }

                            catch(Exception e){

                                e.printStackTrace();

                            }

            }

}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION