Collection interfaces – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Tue, 11 Jul 2023 17:20:12 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg Collection interfaces – Programmerbay https://programmerbay.com 32 32 SortedSet Interface in Java With Program Example https://programmerbay.com/sortedset-interface-in-java-with-program-example/ https://programmerbay.com/sortedset-interface-in-java-with-program-example/#respond Tue, 11 Jul 2023 17:19:23 +0000 https://programmerbay.com/?p=9389

SortedSet is an interface whose implementation class is TreeSet. With the help of implementation classes, we can assign its instance to sortedSet interface. Below is the example:

Program:

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        SortedSet<String> sortedSet = new TreeSet<>() ;  // Creating sortedSet object

        // Adding elements to sorted set object
        sortedSet.add("Example");
        sortedSet.add("Code");
        sortedSet.add("A");

        // Displaying the output
        System.out.println(sortedSet);

        // Removing A element from the set
        sortedSet.remove("A");

        System.out.println(sortedSet);

        // printing first element from the set
        System.out.println(sortedSet.first());

        // printing last element from the set
        System.out.println(sortedSet.last());
    }
}

Output:

[A, Code, Example]
[Code, Example]
Code
Example

Methods of SortSet Interface

Existing methods from Set interface
Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

]]>
https://programmerbay.com/sortedset-interface-in-java-with-program-example/feed/ 0
Set Interface In Java With Program Example https://programmerbay.com/set-interface-in-java-with-program-example/ https://programmerbay.com/set-interface-in-java-with-program-example/#respond Mon, 10 Jul 2023 17:57:29 +0000 https://programmerbay.com/?p=9365 Set is a child interface of the Collection interface that represents an unordered collection where each element is unique and cannot be repeated. It only consists of methods inherited from its parent interface and doesn’t allow duplicate elements. Further, if someone tries to add a duplicate via add() method, then it would return false, signifying the given element is not able to get added. It is part of java.util package.

Screenshot from 2023 07 10 23 23 20
It provides several essential methods that can be used to store, manipulate and search elements in a given set. It depicts a mathematical set and provides its abstraction.

There are various methods which implement the Set interface, including HashSet, LinkedHashSet and TreeSet.
SortedSet and NavigableSet interfaces further extend Set Interface that provides additional behaviour and different implementation to the existing method. NavigableSet is a child interface of SortedSet that provides navigational methods to navigate through a Set. It has a child class named TreeSet which is an implementation of the self-balancing tree.

How to declare and initialise a Set Object in Java?

Set interface provides specification only, in order to create its object, one requires its implementing class i.e HashSet,TreeSet, in order to create an object. With the help of Generics, we can specify the type of object that a Set Collection can store.

Set<T> set = new HashSet<T> ();

Point to Remember:

  • It doesn’t preserve order of inserted elements
  • It allows at most single null element
  •  It doesn’t allow duplicate elements
  • It can have elements of different types

Methods of Set Interface

The methods supported by Set Interface are listed below :

Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

Java Program to demonstrate working of Set interface

Program:

import java.util.HashSet;
import java.util.Set;

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>() ;  // Creating set object
        set.add("The");
        set.add("Programmerbay");
        set.add("Code");
        set.add("Example");

        System.out.println("Printing Added element :: "+set);
        set.add("Code");  //  Adding duplicate element
        System.out.println("Duplicate element not present :: "+set);
        set.remove("Example");  //  Removing duplicate element
        System.out.println("Removing 'Example' element :: "+set);


    }
}

Output:

Printing Added element :: [The, Example, Code, Programmerbay]
Duplicate element not present :: [The, Example, Code, Programmerbay]
Removing 'Example' element :: [The, Code, Programmerbay]

Basic Operations Supported by Set and Its implementing Classes

1) Add Elements :

Set interface specifies add(object) and addAll(CollectionObj) to add elements to a set. It doesn’t preserves insertion order of inserted elements. In contrast, it uses hashing mechanism to store elements where a hash of an element is generated and stored in a hash table. As mentioned before, it doesn’t allow duplicates, but accepts atmost single null value.

Java program to add single element and multiple elements in a Set using add() and addAll() method

Program:

public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>() ; // Creating set object
Collection<String> collection = List.of( "Another","Collection","inserted");

set.add("Programmerbay");

System.out.println("Single Added element :: "+set);

set.addAll(collection); // Adding collection elements, but order will not be preserved

System.out.println("Collection added to set :: "+ set);

}
}

Output:

Single Added element :: [Programmerbay]
Collection added to set :: [inserted, Collection, Programmerbay, Another]

2) Remove Elements:

Set interface offers three methods for this, however, all have different use cases.
1) remove() -> It removes a single element
2) removeAll() -> It accepts a collection object and removes all elements that match the targeted set.
3) retainAll () -> Opposite to removeAll(), it accepts a collection object and persists only those elements that match with the provided collection, other elements that are present in the targeted set get removed.

Java program to remove single element and multiple elements in a Set using remove() and removeAll() method

Program:

public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>() ; // Creating set object
Collection<String> retainObjs = List.of("Programmerbay","Code");
Collection<String> removeAllObj = List.of("Remove1","Remove2");

// Adding random elements
set.add("Remove Me");
set.add("Remove1");
set.add("Remove2");
set.add("Programmerbay");
set.add("Example");
set.add("The");
set.add("Code");


System.out.println("Elements :: "+set);

// removing 'remove Me' from the list
set.remove("Remove Me");

System.out.println("After single remove :: "+set);

set.removeAll(removeAllObj); // remove1 and remove2 stored in removeAllObj would remove elements in set

System.out.println("after removeAll() :: "+ set);

set.retainAll(retainObjs); // Programmerbay and Code stored in reainAllObj would store elements and remove others from the set

System.out.println("after retainAll() :: "+ set);

}
}

Output:

Elements :: [The, Remove1, Remove2, Remove Me, Example, Code, Programmerbay]
After single remove :: [The, Remove1, Remove2, Example, Code, Programmerbay]
after removeAll() :: [The, Example, Code, Programmerbay]
after retainAll() :: [Code, Programmerbay]

4) Iterate over Elements:

There are multiple ways to iterate over elements of a set. These are the following:
1) using iterator
2) Using forEach()
3) Using Java 8 Stream

Java program to iterate over elements of a set.

program:

public class SetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<>() ; // Creating set object

// Adding random elements
set.add("Remove Me");
set.add("Remove1");
set.add("Remove2");
set.add("Programmerbay");
set.add("Example");
set.add("The");
set.add("Code");

Iterator iterator = set.iterator(); // fetching iterator object of the set

System.out.println("Iterating through iterator object :: ");
while (iterator.hasNext()){
System.out.println(iterator.next());
}


// using for each
System.out.println("Iterating through for each loop :: ");

for (String element:
set) {
System.out.println( element);
}

// using Java 8 Stream
System.out.println("Iterating through using java 8 stream :: ");

set.stream().forEach(e -> System.out.println("element :: "+ e));

}
}

Output:

Iterating through iterator object ::
The
Remove1
Remove2
Remove Me
Example
Code
Programmerbay
Iterating through for each loop ::
The
Remove1
Remove2
Remove Me
Example
Code
Programmerbay
Iterating through using java 8 stream ::
element :: The
element :: Remove1
element :: Remove2
element :: Remove Me
element :: Example
element :: Code
element :: Programmerbay


Implementing Classes of Set Interface

HashSet class : Hashset class is a implementing class of Set interface that uses hash table as its underlying data structure. It doesn’t preserves insertion order,meaning, the order in which elements are inserted may differ as it hash code to insert data. It accepts null values.

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new HashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        System.out.println(set);
    }
}

Output:

[Example, Programmerbay]

LinkedHashSet class : It also implements Set interface and exhibits the behavior of doubly linked list. Unlike HashSet, it preserves insertion order.

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new LinkedHashSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        System.out.println(set);
    }
}

Output:

[Programmerbay, Example]

 

TreeSet class : It is a implementation class of SortedSet interface. It resembles tree data structure to store and manage data. It stores data in natural sorting order.

public class SetExample {
    public static void main(String[] args) {
        Set<String> set = new TreeSet<>() ;  // Creating set object
        set.add("Programmerbay");
        set.add("Example");
        System.out.println(set);
    }
}

Output:

[Example, Programmerbay]

 

 

 

]]>
https://programmerbay.com/set-interface-in-java-with-program-example/feed/ 0
Collections in Java With Program Examples https://programmerbay.com/collections-in-java-with-program-examples/ https://programmerbay.com/collections-in-java-with-program-examples/#respond Tue, 04 Jul 2023 12:18:29 +0000 https://programmerbay.com/?p=9306 A collection can be defined as a group of objects (elements) represented as a single entity.
Collections in Java can be viewed as Collection Framework which is the most powerful feature. Collection Framework represents a hierarchy of interfaces and classes that is used to manage, handle and store groups of objects efficiently. It resides within java.util package. It wasn’t initially part of Java and was added later in J2SE 1.2.

Prior to Collection Framework, the legacy classes such as Dictionary, Vector, Stack, and Properties present in the framework, were used to store and manipulate groups of objects.

Java Collection Framework

Collection Framework is a hierarchy of several interfaces and classes that are used to represent a collection. In other words, It can be viewed as an architecture for handling and manipulating collections efficiently.
It comprises of following :
  • Interfaces
  • Classes
  • Algorithms
It works with a reference type only, not with a primitive type.
After the introduction of Generics, the collection framework became more powerful.

What are the advantages of the Collection Framework in Java?

  • Increase in Performance: It provides support for high-performance data structures and algorithms such as dynamic arrays, linked lists, hash tables and trees which are highly efficient.
  • Interoperability: It provides unified behaviour among collections as a result they can operate with one another
  • Easy to Adopt and Use: It represents the hierarchy of interfaces and their implementation classes which can either be used directly or can be used to form a user-defined collection.
  • Standard Array integration: It provides array integration into the collection framework.
  • Reduces Programming Efforts: Each collection class is built upon some underlying data structure based on which it manipulates and works with objects. As a result, it provides several predefined methods for data searching, sorting, insertion, manipulation, and deletion which can be used as-is.

 

Hierarchy of Collection framework in Java

The below hierarchy resembles all the classes and interfaces that formulates Collection Framework architecture.  These classes and interfaces reside within java.util package.

Untitled Diagram
Hierarchy of Collection Framework
Collection Framework
Map Hierarchy of Collection Framework

9 Key interfaces in Collection Framework

1. Collection Interface : It consists all the common methods that can be used by any collection object. It specifies behaviour specifically for List and Set. Therefore, it builds foundation for Collection Framework on which all collections work. It can be considered as root interface of collection framework. No class implements collection interface directly.

It provides core methods such as add(), remove(), isEmpty()  and more, to work with collection objects.

Syntax: 

public interface Collection<T> extends Iterable<T> {
}

 

2. List Interface :

List Interface directly extends Collection. It represents ordered collection or sequence of objects. It specifies a type of data structure where duplicates are allowed and insertion order preserved. ArrayList, LinkedList, Vector and Stack are its implementing classes. Further, It supports implementation for legacy classes that are Vector & Stack which was introduced in Java 1.0 version.

Syntax :

public interface List<T> extends Collection<T> {}

3. Set Interface : A Set interface specifies a type of collection where duplicates are not allowed and insertion order is not preserved. It also extends collection interface. It allows null values and can store elements of different types. HashSet, LinkedHashSet, and TreeSet are the implementing classes of Set.

Syntax : 

public interface Set<T> extends Collection<T> {}

4. SortedSet Interface : It is a child interface of Set. It doesn’t allow duplicates and represents group of elements in some sorting order. It accepts elements of same type that can be ordered in natural sorting order or user-defined order using Comparator.

Syntax:

public interface SortedSet<T> extends Set<T>

 

5. NavigivableSet Interface : It extends SortedSet. It defines various methods to traverse or navigate from one element to other in the given collection. TreeSet is the implementing class of NavigavbleSet.

Syntax:

public interface NavigableSet<T> extends SortedSet<T>{}

6. Queue Interface: It is a child interface of Collection. It represents a group of elements prior to processing or about to be processed in FIFO manner. In other words, it holds elements in a manner of first in first out order before processing. LinkedBlockingQueue and PriorityBlockingQueue are the classes that implements Queue interface.

Syntax:

public interface Queue<T> extends Collection<T>{}

7. Map Interface: 

Map interface represents a group of objects as key value pair, not a group of individual objects. Therefore, Map and Collection interface are two different concepts, as a result, a separate hierarchy is followed in this case for collection Framework. HashMap,linkedHashMap, WeakHashMap, and Hashtable are the implementation class of Map interface.

Syntax:

public interface Map<K,V>

8. SortedMap Interface : It is a child interface of Map. It represents a group of elements in key value pairs where they are stored in some key sorting order.

Syntax:

public interface SortedMap<K,V> extends Map<K,V>{}

9. NavigableMap Interface: It is child interface of SortedMap.Simmilar to NavigableSet, it defines several methods for navigation or traversing purpose. TreeMap is the implementation class of this interface.

Syntax:

public interface NavigableMap<K,V> extends SortedMap<K,V>

Frequently Asked Questions:

1.What is Collection Framework in Java?

Collection Framework is an hierarchy of interfaces and classes to store and manipulate a group of elements efficiently.

2. Why we use Collection Framework in Java?

It provides several high performance classes that are built upon some underlying data structures, offering predefined methods which reduces programming efforts. Therefore, it is used to store and manipulate a group for elements efficiently.

3. Why we need Collection Framework in Java?

There are several limitations of arrays.
An array is not growable in nature ( one needs to define the size of an array at the time of decleration ) therefore, it’s fixed in size and can’t be increased or decreased as per requirement..
Secondly, it supports only elements of same types, as a result, it limits the store elements to the same type.
Lastly, it is not build upon some standard data structure, due to which, there are no predefined methods for data manipulation.
To overcome limitations of Arrays, collection is needed.

4. When was Collection Framework introduced in Java?
It was introduced in JDK 1.2 version.
5. Which package contain all the collection classes ?
java.util package contains all the collection classes.
6. How to import collections in Java?
One can import collection interface or classes by using import java.util.* statement.
7. Which collection contains ordered collection of elements?
List contains ordered collection of elements. ArrayList, Vector and LinkedList are the classes that store ordered collection objects. Ordered collection means sequence, meaning elements gets stored in the same manner in which they are stored.

]]>
https://programmerbay.com/collections-in-java-with-program-examples/feed/ 0