User Professor Hans Noodles
Professor Hans Noodles
Level 41

Collections class

Published in the Java Developer group
Hi! In the past few lessons, we've made great progress in our mastery of ArrayList. However, so far we've only performed the simplest operations: remove, insert, and display. Of course, this doesn't cover the full list of tasks that developers must perform when working with ArrayList. Remember the lesson about arrays and the Arrays class? Java's creators specifically designed this class to handle the most common tasks programmers face when working with arrays. And what about ArrayList? Surely, there's some list of common tasks that need to be performed with it. Have they all been implemented in a specific class, or do we have to write our own implementation each time? Of course, you don't need to write everything yourself. The most common operations involving collections have already been implemented in the special static Collections class. Collections class - 1 In Java, a group of data structures is commonly referred to as a collection. Data can be stored in many different ways. So far, we have only studied the ArrayList class, where data is stored in an array. We'll get acquainted with other collections later. For now, it's enough to just understand that the Collections class is designed to work not only with ArrayList, but also with other types of collections (hence, its name). So, what tasks does the Collections class actually help with when working with ArrayList? The first and most obvious is sorting. In the lesson about arrays, we considered an example with numbers. Now we'll consider an example with strings. The Collections class implements the sort() method for sorting the contents of collections:

public class Main {

   public static void main(java.lang.String[] args) {

       String mercury = new String("Mercury");
       String venus = new String("Venus");
       String earth = new String("Earth");
       String mars = new String("Mars");
       String jupiter = new String("Jupiter");
       String saturn = new String("Saturn");
       String uranus = new String("Uranus");
       String neptune = new String("Neptune");

       ArrayList<String> solarSystem = new ArrayList<>(Arrays.asList(mercury, venus, earth, mars,
               jupiter, saturn, uranus, neptune));
       Collections.sort(solarSystem);
       System.out.println(solarSystem);

   }
}
Output: [Earth, Jupiter, Mars, Mercury, Neptune, Saturn, Uranus, Venus] The strings are sorted alphabetically! But why alphabetically? The String class actually implements the logic that governs how the strings are compared (which happens to be alphabetically). For classes that you create yourself, you can implement your own comparison logic, but we'll talk about this in other lessons. The Collections class also helps you find the minimum and maximum element in an ArrayList. This is done using the min() and max() methods:

public static void main(java.lang.String[] args) {

   ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7));
   System.out.println(Collections.max(numbers));
   System.out.println(Collections.min(numbers));

}
Output: 7 1 Naturally, this is far more convenient than manually writing the code to iterate over all the elements and find the largest/smallest element :) Another very useful method is reverse(). If we had to "flip" the list so the elements went in the opposite order, how would we do it? It probably wouldn't be so easy to write such an algorithm by yourself :) Fortunately, the reverse() method already knows how. Suppose we don't like the fact that the sort() method sorted our planets alphabetically, and we want to reverse their order: from Z to A:

public class Main {

   public static void main(java.lang.String[] args) {

       String mercury = new String("Mercury");
       String venus = new String("Venus");
       String earth = new String("Earth");
       String mars = new String("Mars");
       String jupiter = new String("Jupiter");
       String saturn = new String("Saturn");
       String uranus = new String("Uranus");
       String neptune = new String("Neptune");

       ArrayList<String> solarSystem = new ArrayList<>(Arrays.asList(mercury, venus, earth, mars,
               jupiter, saturn, uranus, neptune));
       Collections.sort(solarSystem);
       Collections.reverse(solarSystem);
       System.out.println(solarSystem);

   }
}
Output: [Venus, Uranus, Saturn, Neptune, Mercury, Mars, Jupiter, Earth] We've been doing a lot of talking about sorting, the order of the elements, etc. But what if we had the opposite objective? For example, suppose we're trying to implement a bingo game. We add 100 numbers to the drum. They should appear on the screen one at a time. The first player to cross out all the numbers on his ticket wins. This is easy to implement using the shuffle() method:

public class Main {

   public static void main(java.lang.String[] args) {

       ArrayList<Integer> bingoDrum = new ArrayList<>(100);
       for (int i = 1; i <= 100; i++) {

           bingoDrum.add(i);// add the numbers 1 to 100 to the drum
       }

       Collections.shuffle(bingoDrum);// Mix it up
       System.out.println ("Your attention, please! Here are the first 10 numbers from the drum!");
       for (int i = 0; i < 10; i++) {

           System.out.println(bingoDrum.get(i));
       }

   }
}
Output: Your attention, please! Here are the first 10 numbers from the drum! 32 61 4 81 25 8 66 35 42 71 It's that easy! The problem is solved, and our part of the game is written :) Now let's imagine a different situation. Previously, we created a solarSystem list that contained the planets. And it seems to suit us in every way but one: you can delete items from it and add new ones! This is clearly not the behavior we expect: The solar system should be unchangeable in our program. The Collections class has a very interesting method: unmodifiableList(). It creates an immutable list from the list passed as an argument. You can't add or delete items from this list. When dealing with the list of planets in the solar system, this is exactly what we want!

public class Main {

   public static void main(java.lang.String[] args) {

       String mercury = new String("Mercury");
       String venus = new String("Venus");
       String earth = new String("Earth");
       String mars = new String("Mars");
       String jupiter = new String("Jupiter");
       String saturn = new String("Saturn");
       String uranus = new String("Uranus");
       String neptune = new String("Neptune");

       List<String> solarSystem = Collections.unmodifiableList(new ArrayList<>(Arrays.asList(mercury, venus, earth, mars,
               jupiter, saturn, uranus, neptune)));
       solarSystem.add("Pluto");// Try to add a new element
   }
}
Output: Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableCollection.add(Collections.java:1075) at Main.main(Main.java:21) This is an error: you can't add anything to solarSystem! The only thing you need to pay attention here is the fact that this method returns List<> (not ArrayList<>), since this type is common for all kinds of lists. Another quite common situation that can easily happen is for the programmer to add elements in the wrong order. If this happens and we find that Mercury and Neptune are mixed up, we can correct this mistake using the swap() method:

public class Main {

   public static void main(java.lang.String[] args) {

       String mercury = new String("Mercury");
       String venus = new String("Venus");
       String earth = new String("Earth");
       String mars = new String("Mars");
       String jupiter = new String("Jupiter");
       String saturn = new String("Saturn");
       String uranus = new String("Uranus");
       String neptune = new String("Neptune");

       ArrayList<String> solarSystem = new ArrayList<>(Arrays.asList(neptune, venus, earth, mars
       , jupiter, saturn, uranus, mercury));// The planets are in the wrong order
       System.out.println(solarSystem);

       Collections.swap(solarSystem, solarSystem.indexOf(mercury), solarSystem.indexOf(neptune));
       System.out.println(solarSystem);

   }
}
We pass to the swap() method our list and the indices of the two elements that need to be swapped. Note that the method works with indices, not references. So, here we had to use the ArrayList.indexOf() method. Output: [Neptune, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Mercury] [Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune] Finally, we'll get acquainted with a very interesting method: disjoint(). It checks whether two collections intersect, i.e., whether they have at least one identical element. If they do not, it returns true. It they do, then it returns false

public class Main {

   public static void main(java.lang.String[] args) {

       String mercury = new String("Mercury");
       String venus = new String("Venus");
       String earth = new String("Earth");
       String mars = new String("Mars");
       String jupiter = new String("Jupiter");
       String saturn = new String("Saturn");
       String uranus = new String("Uranus");
       String neptune = new String("Neptune");

       ArrayList<String> solarSystemPart1 = new ArrayList<>(Arrays.asList(mercury, venus, earth, mars));
       ArrayList<String> solarSystemPart2 = new ArrayList<>(Arrays.asList(jupiter, saturn, uranus, neptune));

       System.out.println(Collections.disjoint(solarSystemPart1, solarSystemPart2));

   }
}
As you can see, our two lists have completely different elements, so the program outputs true. This is an interesting and very useful class. Like Arrays, it does a lot of routine, tedious work for us, letting us focus on other things.
Comments (32)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
FrogTea Level 10
6 August 2021
👍
Sinisa Level 11, Banja Luka, Bosnia and Herzegovina
9 March 2021
Use this in order to avoid multiple nested loop-crap.
Karas Level 19, Tampa, United States
27 September 2020
Does anyone has the feeling this article could have helped A LOT in prior exercises? Or that some of the exercises are actually already solved by these? Something to think about. Pluto comes and goes from the Solar System. LOL
Jaki Taki Level 16, Poznan, Poland
3 September 2020
Yes, I also find this article very informative.
umidbek Level 17, Tashkent, Uzbekistan
26 August 2020
I have a question about disjoint() method. In the exampe above we can see that there are 8 variables and it is divided two parts equally: ArrayList<String> solarSystemPart1 = new ArrayList<>(Arrays.asList(mercury, venus, earth, mars)); ArrayList<String> solarSystemPart2 = new ArrayList<>(Arrays.asList(jupiter, saturn, uranus, neptune)); the question is that does this method always uses even number variables, or it also may use odd variables if it does how this method compare odd number variables
Agent Smith Level 38
17 August 2020
"The solar system should be unchangeable in our program." Pluto sends its regards! :D
carolina Level 12, Cordoba, Argentina
5 August 2020
Very interesting!
Peter Schrijver Level 23, Hilversum, Netherlands
5 June 2020
very useful, save a lot of work.Easy to implement
Татьяна Матвеева Level 8, Moscow, Russian Federation
11 May 2020
Very useful information, I wish I had known this before
David Level 29, Paris, France
28 March 2020
Very Good