首页 > 解决方案 > 从arraylist返回字符串

问题描述

假设我有一堂课

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;
    }
}

我有这个类的arraylist

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

我在数组列表中添加了一些元素

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

当我在数组列表中搜索特定字符串时,我希望能够返回一个字符串。我的意思是:

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

我怎样才能做到这一点?

标签: javaarraylist

解决方案


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.


推荐阅读