Frequently Performed Operations in List

Frequently Performed Operations in List

In our previous article, we had discussed about List interface, types of lists, internal working along with their advantages and disadvantages. (Please read here).

In this article we can discuss some of the most frequently performed list operations and which has to be remembered at all times.

Arrays.asList:

When we use Arrays.asList, it converts the array elements into a fixed size list. Let us see an example,

Now we have a fixed size list -> stringList.

What will be the output?

Now let us try to add an element “Echo” to the above list,

As a common expectation it should add the element to the list, But unfortunately we will get an exception when we try to add an element to the above list,

We will get the same exception when we try to remove an element from the above list, but why?

But, Why?

When we use Arrays.asList -> it returns a fixed size list which limits to perform add / remove operations.

Updating is possible:

Even if we have the limitation to add / remove an element, we can still update the list as the list size is not going to change.

Here is the sample code,

Now for other examples, let us create 2 lists,

We have 2 lists where 5 and 11 are common elements and we have 2 elements 90 in second list as duplicates.

Max and Min in the list:

How to find the maximum element and minimum element in the list ?

We can use ,

What is the list is empty or if it is a generic list when trying Collections to get min or max?

If the list is empty we will get NoSuchElementException and if the list is generic (list contains mix of string, integers etc…) it will throw ClassCastException.

How can we concatenate or add two lists?

Example, if we can to add both the lists intList1 and intList2 , we can use

This will combine all the elements to both lists together.

How to Concatenate or Add two lists avoiding duplicates?

There are two ways of doing this,

Type 1:

We can use streams to get distinct elements,

Type 2:

 

Replacing all the occurrences of a element in the list:

Consider in the intList2, we have element 90. Now if we want to replace all the occurrences of element 90 with 100 in list2, how can this be done?

This will replace element 90 to 100 in intList2.

How can we make a list Synchronized?

The lists are not thread-safe by default, suppose if we want to make the list threadsafe, we can use

SingletonList vs UnmodifiableList:

We have Collections.singletonList and Collections.unmodifiableList. So what is the difference between these two?

Collections.singletonList:  will take single element or object and makes it an immutable list with that single element or object.

Collections.unmodifiableList: Will make the list as an read-only list, when any add or remove operations are performed, it will throws UnSupportedOperationException

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *