Banele Nqeto
Banele Nqeto

Reputation: 1

Getting specific type of objects from list in java

I have the Object

 List<Object> mylist = new ArrayList<Object>();
 mylist.add(20);
 mylist.add("Banele");

and from mylist i want to only

System.out.println("Banele");

meaning string not integer (20).how can i do this please help me

Upvotes: 0

Views: 83

Answers (4)

Aniket Thakur
Aniket Thakur

Reputation: 68935

An alternative to the usage of instanceof

    for (Object object : mylist) {
        if(object.getClass().equals(String.class)){
            System.out.println(object);
        }
    }

Upvotes: 0

blackpanther
blackpanther

Reputation: 11486

What about the following?

for (Object item : myList) {
    if (item instanceof String) {
         // retrieve.
         String myString = (String) item;
    }
}

Upvotes: 0

sunysen
sunysen

Reputation: 2351

try

for (Object object : mylist) {
    if(object instanceof  String){
        System.out.println(object);
    }
}

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 121998

Check the object type ,while iterating.

 for (Object object : mylist) {
    if(object instanceof  String){
        System.out.println(object);
    }
}

Upvotes: 3

Related Questions