Jesse Haniel
Lead Software Architect at Tribunal de Justiça da Paraíba

Collections class in Java

Published in the Java Developer group
members
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 (38)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Ocean
Level 13 , China, Hong Kong
31 July, 05:35
So convenient.
To be brave #10900452
Level 14 , Пекин, United States
10 January, 13:58
the class is so funy!
Aldo Luna Bueno
Level 28 , Peru
9 December 2021, 03:37
Supongo que el método disjoint() usa internamente el método equals(), por lo que habría que sobreescribirlo primero si no estamos manejando objetos String.
Victor Omoha
Level 8 , Raleigh , United States
11 November 2021, 14:13
Interesting
FrogTea
Level 20
6 August 2021, 13:51
👍
Sinisa
Level 11 , Banja Luka, Bosnia and Herzegovina
9 March 2021, 18:02
Use this in order to avoid multiple nested loop-crap.
Karas Java Developer
27 September 2020, 23:57
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
Andrei
Level 41
5 November 2020, 10:18
I believe that having done the exercises before, and trying to figure them out it gave us some reference. So now, when we read this article we think "ah, yes, this is how I could have applied this principle in that program" etc, making it easier for us to understand the information presented. It would've been easier but I think in the long run this way is better.
Guanting Liu
Level 16 , Springfield, United States
12 November 2020, 06:55
They are actually easier method for previous tasks,but codegym requires you to use more slow and costly method to do it instead of using tricks XD.
Khongpak Phupkdee
Level 15 , Chiangrai, Thailand
6 May 2021, 06:45
LOL 😆 I think so
Jaki Taki
Level 16 , Poznan, Poland
3 September 2020, 08:42
Yes, I also find this article very informative.
umidbek
Level 17 , Tashkent, Uzbekistan
26 August 2020, 18:17
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
Onur Bal
Level 27 , Istanbul, Turkey
11 September 2020, 19:00
It doesn't check one-to-one (i.e. whether solarSystemPart1.get(1) == solarSystemPart2.get(1)), but rather whether they have ANY element in common at all, so the number of elements does not matter at all.
Andrei
Level 41
5 November 2020, 10:18
Great question!
P.B.Kalyan Krishna
Level 24 , Guntur, India
29 March, 07:52
I think it just checks the two lists for common elements. Whether there are even number of elements or odd number of elements, does not matter. It returns false if there are common elements in the two lists, else it returns true! I think it also works if there are even number of elements in one list and odd number of elements in the other list.
Romant QA
9 May, 18:26
And null elements in both collections make it respond me false?
Agent Smith
Level 38
17 August 2020, 13:42
"The solar system should be unchangeable in our program." Pluto sends its regards! :D
Chandan Thapa
Level 22 , Dubai, United Arab Emirates
23 October 2020, 09:08
hanging out with it's other dwarf planets :))