Core Java

Find Java Set Element By Index

In Java, Sets do not permit the inclusion of duplicate elements. Key implementations of the Set interface encompass HashSet, TreeSet, and LinkedHashSet. Let us delve into how we can we find a Java Set Element by its index.

1. Introduction

The Set interface in Java is part of the Java Collections Framework and represents an unordered collection of unique elements. It does not allow duplicate elements, making it suitable for scenarios where distinct values are essential.

Set ImplementationDescription
HashSetHashSet is an implementation of the Set interface that uses a hash table for storage. It does not guarantee the order of elements and offers constant-time performance for basic operations, like add, remove, and contains. Key features:

  • Does not maintain the order of elements.
  • Permits null elements.
  • Offers constant-time performance for basic operations.
TreeSetTreeSet is an implementation of the Set interface that uses a self-balancing binary search tree (Red-Black tree) for storage. It maintains elements in sorted order, allowing for efficient retrieval and range operations. Key features:

  • Maintains elements in sorted order.
  • Does not permit null elements.
  • Offers logarithmic time complexity for basic operations.
LinkedHashSetLinkedHashSet is an implementation of the Set interface that extends HashSet and maintains a doubly linked list of the elements. It combines the features of both HashSet and Linked List, providing predictable iteration order. Key features:

  • Maintains the order of elements as they are inserted.
  • Permits null elements.
  • Offers linear time complexity for basic operations.

2. Why Sets Do Not Provide an indexOf()?

Sets in Java do not provide an indexOf() method primarily because the concept of an index is associated with ordered collections, and sets, by definition, do not guarantee any specific order of elements.

The indexOf() method is commonly used with ordered collections like lists, where each element has a specific index based on its position in the list. Lists support access to elements by index, and the indexOf() method is used to find the index of a particular element within the list.

In contrast, sets in Java, such as HashSet, TreeSet, and LinkedHashSet, focus on ensuring uniqueness and do not maintain a specific order of elements. The lack of order means that there is no inherent index associated with elements in a set. When you iterate over a set, you’ll get elements in an undefined order.

If you need to find the position of an element in a collection, you want to consider using a List or another ordered data structure. Alternatively, if you are working with sets and need to check for the existence of an element, you can use the contains() method, which is provided by the Set interface.

Here’s an example demonstrating the use of contains() with a HashSet:

package com.jcg.example;

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

public class Example {
    public static void main(String[] args) {
        Set<String> stringSet = new HashSet<>();
        stringSet.add("Apple");
        stringSet.add("Banana");
        stringSet.add("Orange");

        String targetElement = "Banana";

        if (stringSet.contains(targetElement)) {
            System.out.println(targetElement + " is present in the set.");
        } else {
            System.out.println(targetElement + " is not present in the set.");
        }
    }
}

3. Set Utility: getIndexInSet()

In Java, the Set interface does not provide an indexOf() method, but you can create a utility method to achieve similar functionality. Below is an example of a utility method named getIndexInSet() that finds the index of an element in a Set.

package com.jcg.example;

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

public class SetUtility {

    public static <T> int getIndexInSet(Set<T> set, T targetElement) {
        int index = 0;

        // Iterate through the set to find the index
        Iterator<T> iterator = set.iterator();
        while (iterator.hasNext()) {
            T element = iterator.next();
            if (element.equals(targetElement)) {
                return index;
            }
            index++;
        }

        // Element not found
        return -1;
    }

    public static void main(String[] args) {
        // Example usage
        Set<String> stringSet = new HashSet<>();
        stringSet.add("Apple");
        stringSet.add("Banana");
        stringSet.add("Orange");

        String targetElement = "Banana";
        int index = getIndexInSet(stringSet, targetElement);

        if (index != -1) {
            System.out.println(targetElement + " is present in the set at index: " + index);
        } else {
            System.out.println(targetElement + " is not present in the set.");
        }
    }
}

The getIndexInSet() method iterates through the Set and returns the index of the target element if found, or -1 if not found.

4. Custom LinkedHashSet: IndexedLinkedHashSet

Here is an example of a custom implementation of LinkedHashSet in Java named IndexedLinkedHashSet. This implementation extends LinkedHashSet and includes a utility method named getIndexInSet() to get the index of an element in the set.

package com.jcg.example;

import java.util.LinkedHashSet;
import java.util.Iterator;

public class IndexedLinkedHashSet<E> extends LinkedHashSet<E> {

    public int getIndexInSet(E targetElement) {
        int index = 0;

        // Iterate through the set to find the index
        Iterator<E> iterator = iterator();
        while (iterator.hasNext()) {
            E element = iterator.next();
            if (element.equals(targetElement)) {
                return index;
            }
            index++;
        }

        // Element not found
        return -1;
    }

    public static void main(String[] args) {
        // Example usage
        IndexedLinkedHashSet<String> stringSet = new IndexedLinkedHashSet<>();
        stringSet.add("Apple");
        stringSet.add("Banana");
        stringSet.add("Orange");

        String targetElement = "Banana";
        int index = stringSet.getIndexInSet(targetElement);

        if (index != -1) {
            System.out.println(targetElement + " is present in the set at index: " + index);
        } else {
            System.out.println(targetElement + " is not present in the set.");
        }
    }
}

The IndexedLinkedHashSet class extends LinkedHashSet and adds the getIndexInSet() method, allowing you to get the index of an element in the set.

5. Apache Commons Collections: ListUtils.indexOf()

Apache Commons Collections library provides useful utilities for working with collections in Java. The ListUtils.indexOf() method can be used to find the index of an object in a list or collection.

Below is an example demonstrating how to use ListUtils.indexOf() to get the index of an element in a collection.

package com.jcg.example;

import org.apache.commons.collections4.ListUtils;

import java.util.ArrayList;
import java.util.List;

public class ApacheCommonsExample {

    public static void main(String[] args) {
        // Example usage
        List<String> stringList = new ArrayList<>();
        stringList.add("Apple");
        stringList.add("Banana");
        stringList.add("Orange");

        String targetElement = "Banana";

        // Get the index using ListUtils.indexOf()
        int index = ListUtils.indexOf(stringList, object -> object.equals(targetElement));

        if (index != -1) {
            System.out.println(targetElement + " is present in the list at index: " + index);
        } else {
            System.out.println(targetElement + " is not present in the list.");
        }
    }
}

In this example, ListUtils.indexOf() is used to find the index of the target element in the list.

6. Conclusion

In conclusion, we explored various aspects of Java sets and techniques for retrieving the index of an element within these collections. Initially, we delved into the characteristics of Java sets, highlighting their emphasis on uniqueness and lack of a predefined order. Understanding that sets, including HashSet, TreeSet, and LinkedHashSet, do not inherently support the indexOf() method due to their unordered nature, we explored alternatives for achieving similar functionality.

We first demonstrated a utility method named getIndexInSet(), applicable to any Set implementation, offering a manual iteration approach to find an element’s index. Subsequently, we extended the discussion to introduce a custom implementation, the IndexedLinkedHashSet, which extends LinkedHashSet and incorporates a dedicated getIndexInSet() method. This approach allows users to seamlessly obtain the index of an element within the set.

Moreover, we acknowledged the utility of Apache Commons Collections in simplifying such tasks. The example showcased the use of ListUtils.indexOf() from Apache Commons Collections to find the index of an element in a list or collection, providing an alternative for those preferring external libraries.

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button