假设我有一个类
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<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.
我该怎么做?
type.stream()
.filter(c -> c.getType().equals("test"))
.collect(Collectors.toList());
正如其他人在评论中建议的那样,当您使用Map而不是ArrayList时,这将非常容易。但在你的情况下,为了实现你所需要的,你可以遵循以下步骤。当你在Java8中使用流时,这将非常容易。但我将提供一个简单的解决方案,你可以在没有流的情况下实现。
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;
}
}
现在,根据结果中包含的值,您可以继续您的工作。若迭代后结果为null,则表示并没有找到匹配项。