简体   繁体   中英

Return string from arraylist

Lets say I have a class

public class Ttype{
    
    private String type = "";

    public Ttype(String type) {
        
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

and I have arraylist of this class

ArrayList<Ttype> type = new ArrayList<Ttype>();

I have added some elements to the arraylist

type.add( new new Ttype("Hello"));
type.add( new new Ttype("Bye"));
type.add( new new Ttype("Hi"));

I want to be able to return a string when I search for specefic string in the arraylist. What I mean by that is:

Ttype t = type.get("Hello"); //t will be set to "hello" if hello is in the arraylist.

How can I do that?

type.stream()
  .filter(c -> c.getType().equals("test"))
  .collect(Collectors.toList());

Well as others suggested in comments this will be much easy when you use a Map rather than ArrayList. But in your case to achieve what you need you can follow the below steps.This will be much easy when you use streams in Java 8.But I will provide a simple solution which you can achieve without streams.

Ttype result = null;//To store if an object found 
String searchTxt = "Hello";

for(Ttype temp:type){//Iterating through the list find a match

   if(temp.type.equlas(searchTxt)){
       result = temp;
   }

}

Now based on the value which contains in the result you can continue your work.If result is null after the iteration it means there is no matching item found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM