Ajay thakur
Ajay thakur

Reputation: 13

How to get index of element from vector which contain objects in java

Below is the sample code in which i want to find the index object which contain str="test" from vector which holds objects.

class Abc{
        String str1;
        String str2;
}
class Test{
        Vector vector = new Vector();
        Abc obj1 = new Abc();
        obj1.str1 = "test";
        Abc obj2 = new Abc();
        obj2.str1 = "test2";
        vector.add(obj1);
        vector.add(obj2);
        //now i want index of that object which have str="test"
        //it should give 0 (object 0 contain test)
       //with loop we can easily get but do we get that by using //streams or indexOf method
}

Upvotes: 0

Views: 639

Answers (1)

magicmn
magicmn

Reputation: 1914

Vector is a very outdated class and most of the time you want to use an ArrayList or any other List implementation instead. Neither indexOf nor Stream will be a big help here.

You could use a stream to create a new list and then use indexOf, but while it looks shorter than a traditional loop it's way more expensive.

List<Abc> list = new ArrayList<>();
// Fill list with values
List<String> strList = list.stream().map(abc -> abc.str1).collect(Collectors.toList());
strList.indexOf("test2");

Upvotes: 1

Related Questions