gpt4 book ai didi

java - 如何使用流获取数组列表的特定值

转载 作者:行者123 更新时间:2023-12-02 01:10:09 26 4
gpt4 key购买 nike

我有一个 Person 的 ArrayList,按 ids 排序,0 作为 id:1,1 作为 id:2 等,我只想使用流在另一个 ArrayList 中获取其中的一些这是我尝试过的方法,但似乎不起作用:

public ArrayList<Person> getPersonfoById(int... ids) {
if (IntStream.of(ids).anyMatch(id -> id > totalpersonnumber)) {
throw new IllegalArgumentException("the given person id" + Arrays.asList(IntStream.of(ids).filter(i -> i >= totalpersonnumber).boxed().toArray()) + " dosen't exist in " + fileName);
}
try (IntStream stream = Arrays.stream(ids)) {
return (ArrayList<Pokemon>) stream.boxed().map(x -> myArrayOfPerson.get(x))
.collect(Collectors.toList());
}
}

最佳答案

由于所选 ID 的输入可能会有所不同,因此最好的方法是在过滤器的谓词中使用 List::contains:

// Get a list of ids at the beginning once and use with each iteration
List<Integer> idsList = Arrays.stream(ids).boxed().collect(Collectors.toList());

List<Person> personList myArrayOfPerson.stream() // Stream<Person>
.filter(person -> idsList.contains(person.getId())) // Stream<Person> of the given ids
.collect(Collectors.toList()); // List<Person>

在该解决方案中,id 是对象 Person一部分,而不是由 List 的行为驱动 这不是一个好的做法。

但是,如果您坚持将它们放在 List 中的某些位置,则需要采取一些不同的方法:

List<Person> personList = Arrays.stream(ids)             // IntStream
.boxed() // Stream<Integer>
.map(myArrayOfPerson::get) // Stream<Person>
.collect(Collectors.toList()); // List<Person>

这是一种快速失败方法,不会处理越界的 id。您应该知道 List::get 可能会抛出 IndexOutOfBoundsException,因此为了避免这种情况,请过滤掉不适合列表的 ids尺寸:

List<Person> personList = Arrays.stream(ids)             // IntStream
.filter(id -> id > 0 && id < myArrayOfPerson.size()) // IntStream (wanted ids only)
.boxed() // Stream<Integer>
.map(myArrayOfPerson::get) // Stream<Person>
.collect(Collectors.toList()); // List<Person>

另一种方法是为异常 ID 返回空对象或记录消息或以其他方式处理它,这超出了本答案的范围。

关于java - 如何使用流获取数组列表的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59524242/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com