我有一个包含Book对象的ArrayList,如何根据其属性获取特定对象的索引" ID"价值?
public static void main(String[] args) {
ArrayList<Book> list = new ArrayList<>();
list.add(new Book("foods", 1));
list.add(new Book("dogs", 2));
list.add(new Book("cats", 3));
list.add(new Book("drinks", 4));
list.add(new Book("sport", 5));
int index =
}
本书课:
public class Book {
String name;
int id;
public Book(String name, int Id) {
this.name=name;
this.id=Id;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
答案 0 :(得分:2)
您可以使用IntStream
生成索引,然后对给定条件使用filter
操作,然后使用.findFirst()...
检索索引,如下所示:
int index = IntStream.range(0, list.size())
.filter(i -> list.get(i).id == searchId)
.findFirst()
.orElse(-1);
答案 1 :(得分:1)
作为Java 8工作解决方案的补充,对于那些使用8之前的Java版本的人来说,有一个解决方案:
public function actionImageUpload()
{
$model = new MyNews();
$imageFile = UploadedFile::getInstance($model, 'img');
$directory = Yii::getAlias('@uploadDir');
if ($imageFile != null) { //can't saveAs() file into my ../img/temp/ folder
$uid = 'qqqq';
$fileName = $uid . '.' . $imageFile->extension;
$filePath = $directory . $fileName;
if ($imageFile->saveAs($filePath)) {
Yii::$app->session->setFlash('success','The file has been uploaded successfuly');
return $this->redirect('index');
}
}
}
答案 2 :(得分:1)
这正是您所寻找的:
private static int findIndexById(List<Book> list, int id) {
int index = -1;
for(int i=0; i < list.size();i++){
if(list.get(i).id == id){
return i;
}
}
return index;
}
并称之为:
int index = findIndexById(list,4);
即使您使用的是Java 8,也不建议您使用Java。 for循环比流更快。 Reference