如何在包含多个元素的 objects 列表中找到 Java 用于打印的特定元素?
How do I find in Java a specific element, for printing, in a list of objects with multiple elements?
长话短说,我解析了 here 中的所有 json
进入 object 的列表。但是我在尝试查找特定 object 时遇到了问题。在网上搜索列表的所有例子我似乎无法得到它。
我让用户在int checkId 和checkUserId 中分别输入一个数字,然后进行比较。如果匹配,它应该打印出标题。
Iterator < Post > iter = posts.iterator();
while (iter.hasNext()) {
if (Objects.equals(iter.next().getUserId(), checkUserId)) {
System.out.println("found UserId");
if (Objects.equals(iter.next().getId(), checkId)) {
System.out.println("found Id");
//prints the title of object
}
}
}
然后我尝试使用流
List<Post> result = posts.stream()
.filter(title -> checkId.equals(getId()))
.findAny()
.orElse(null);
我从这个伟大的人那里克隆的所有代码。 https://github.com/danvega/httpclient-tutorial
您的第一次尝试没有成功,因为您通过调用 next
在每次迭代中将迭代器推进两次。相反,存储 Iterator#next
的结果并使用它。
Iterator<Post> iter = posts.iterator();
while(iter.hasNext()){
Post post = iter.next();
if(Objects.equals(post.getUserId(), checkUserId)) {
System.out.println("found UserId");
System.out.println(post.getTitle());
}
}
有流:
List<String> titles = posts.stream().filter(post-> checkId.equals(post.getId()))
.map(Post::getTitle).collect(Collectors.toList());
titles.forEach(System.out::println);
长话短说,我解析了 here 中的所有 json 进入 object 的列表。但是我在尝试查找特定 object 时遇到了问题。在网上搜索列表的所有例子我似乎无法得到它。
我让用户在int checkId 和checkUserId 中分别输入一个数字,然后进行比较。如果匹配,它应该打印出标题。
Iterator < Post > iter = posts.iterator();
while (iter.hasNext()) {
if (Objects.equals(iter.next().getUserId(), checkUserId)) {
System.out.println("found UserId");
if (Objects.equals(iter.next().getId(), checkId)) {
System.out.println("found Id");
//prints the title of object
}
}
}
然后我尝试使用流
List<Post> result = posts.stream()
.filter(title -> checkId.equals(getId()))
.findAny()
.orElse(null);
我从这个伟大的人那里克隆的所有代码。 https://github.com/danvega/httpclient-tutorial
您的第一次尝试没有成功,因为您通过调用 next
在每次迭代中将迭代器推进两次。相反,存储 Iterator#next
的结果并使用它。
Iterator<Post> iter = posts.iterator();
while(iter.hasNext()){
Post post = iter.next();
if(Objects.equals(post.getUserId(), checkUserId)) {
System.out.println("found UserId");
System.out.println(post.getTitle());
}
}
有流:
List<String> titles = posts.stream().filter(post-> checkId.equals(post.getId()))
.map(Post::getTitle).collect(Collectors.toList());
titles.forEach(System.out::println);