Close

Java Collections - How to find the index of an element in a Set?

Java Collections Java 

Index of an element of a java.util.Set can be found by converting it to an a java.util.List:

package com.logicbig.example;

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

public class SetIndexExample {

public static void main(String[] args) {
Set<Integer> mySet = new HashSet<>();
mySet.add(5);
mySet.add(7);
mySet.add(-4);
mySet.add(2);
System.out.format("Set: %s%n", mySet);

int i = new ArrayList<>(mySet).indexOf(2);
System.out.format("index of 2: %d%n", i);
}
}

Output

Set: [2, -4, 5, 7]
index of 2: 0




In case of a SortedSet:

package com.logicbig.example;

import java.util.ArrayList;
import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetIndexExample {

public static void main(String[] args) {
SortedSet<Integer> mySet = new TreeSet<>();
mySet.add(5);
mySet.add(7);
mySet.add(-4);
mySet.add(2);
System.out.format("Set: %s%n", mySet);

int i = new ArrayList<>(mySet).indexOf(2);
System.out.format("index of 2: %d%n", i);
}
}

Output

Set: [-4, 2, 5, 7]
index of 2: 1




See Also