List中查找元素的索引

使用 Stream API,若找到匹配的元素,返回第一次出现的索引,否则 -1

import java.util.List;
import java.util.Objects;
import java.util.stream.IntStream;
 
class Main
{
    public static void main(String[] args)
    {
        List<People> peopleList = Arrays.asList(People.builder().id(1L).name("小明").build(),
                People.builder().id(2L).name("小红").build(),
                People.builder().id(3L).name("小同").build());

        Long target = 2L;
        int index = IntStream.range(0, peopleList.size())
                .filter(i -> Objects.equals(peopleList.get(i).getId(), target))
                .findFirst()
                .orElse(-1);
        System.out.println(index); # 1

        Long target2 = 9L;
        int index2 = IntStream.range(0, peopleList.size())
                .filter(i -> Objects.equals(peopleList.get(i).getId(), target2))
                .findFirst()
                .orElse(-1);
        System.out.println(index2); # -1
    }
}

@Builder
@Data
public class People{
    private Long id;
    private String name;
}

你可能感兴趣的:(java)