英文:
How to get an element of an object from a linkedlist using streams in Java
问题
Consider a class ABC
class ABC {
int id;
String text;
// getter & setter methods..
}
A list of instances of ABC is collected in a linked list.
LinkedList<ABC>
Now, I have an input int n. Based on the input n, I need to check the list of ABC instances where I can get a match (n == id)
.
Based on the match, I will have to retrieve the corresponding String text from the same instance of ABC.
For example:
LinkedList<ABC> list = new LinkedList<>();
list.add(new ABC(1, "Eagle"));
list.add(new ABC(2, "Tiger"));
list.add(new ABC(3, "Rabbit"));
If the input n = 3,
then I need to get the below result:
"Rabbit"
I tried to use streams as below:
list.stream().filter(p -> p.getId() == n).map(ABC::getText);
But I want only String as an answer from the above line.
英文:
Consider a class ABC
class ABC{
int id;
String text;
getter & setter methods..
}
A list of instances of ABC is collected in a linked list.
Linkedlist<ABC>
Now, I have an input int n. Based on the input n, I need to check list of ABC instances where I can get a match (n == d)
Based on the match, I will have to retrieve the corresponding String text from the same instance of ABC.
For example:
Linkedlist<ABC> list = new Linkedlist<>();
list.add(new ABC(1,"Eagle");
list.add(new ABC(2,"Tiger");
list.add(new ABC(3,"Rabbit");
if the input n = 3,
then I need to get the below result:
"Rabbit"
I tried to use streams as below:
list.stream().filter(p -> p.getId() == n).map(ABC:: getText);
But I want only String as an answer from the above line.
答案1
得分: 1
- 使用
findFirst
获取一个ABC
实例,它返回一个Optional<ABC>
- 使用
orElseThrow
获取真正的ABC
或在没有匹配项时引发异常 - 使用
getText
一次来获取其文本
String result = list.stream().filter(p -> p.getId() == n).findFirst().orElseThrow().getText();
英文:
Use
findFirst
to get oneABC
instance, it returns anOptional<ABC>
orElseThrow
to get the realABC
or raise an exception is no matchgetText
once to get its text
<!-- -->
String result = list.stream().filter(p -> p.getId() == n).findFirst().orElseThrow().getText();
答案2
得分: 1
使用 findFirst()
并注意返回类型是 Optional 实例。
String result = list.stream()
.filter(p -> p.getId() == n)
.map(ABC::getText)
.findFirst()
.orElse(null);
英文:
use findFirst()
and be aware return type is an Optional instance.
String result = list.stream()
.filter(p -> p.getId() == n)
.map(ABC::getText)
.findFirst()
.orElse(null);
答案3
得分: 1
你可以使用 Stream#findFirst,以及 Optional#orElse。
System.out.println(
list.stream().filter(abc -> abc.id == n)
.map(abc -> abc.text)
.findFirst()
.orElse(null));
输出,其中 n 为 3。
Rabbit
英文:
You can use Stream#findFirst, with the Optional#orElse.
System.out.println(
list.stream().filter(abc -> abc.id == n)
.map(abc -> abc.text)
.findFirst()
.orElse(null));
Output, where n is 3.
Rabbit
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论