英文:
Java 8 Stream filter object list by key. Exclude key that are in List & get String
问题
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// Your code and data
List<Selectable> tenants = List.of(
new Tenant(34L, "House"),
new Tenant(35L, "Care"),
new Tenant(36L, "Villa"),
new Tenant(37L, "Safe")
);
List<Long> idTenantsWithAlerts = List.of(34L, 36L);
// Filtering and creating the result String
String tenantsNoAlerts = tenants.stream()
.filter(tenant -> !idTenantsWithAlerts.contains(tenant.getId()))
.map(Selectable::getName)
.collect(Collectors.joining(", "));
System.out.println(tenantsNoAlerts);
}
}
interface Selectable {
Long getId();
String getName();
}
class Tenant implements Selectable {
private Long id;
private String name;
public Tenant(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
英文:
I want to exclude the objects from a list with the id's contained in another list of Id's and get a String of field names." Care, Safe"
Example:
public interface Selectable {
Long getId();
String getName();
}
I have a list<Selectable> tenants
id, name
34, "House"
35, "Care"
36, "Villa"
37, "Safe"
and another List<Long> idTenantsWithAlerts
id
34
36
I need the result String tenantsNoAlerts to be "Care, Safe"
I don't have many experience with java8 streams, so I tried same filter, map and reduce ... but no luck.
答案1
得分: 6
你可以通过 Id
进行列表过滤,然后使用 map
,再结合连接收集器进行 collect
,以将 Stream
缩减为一个 String
。
List<Selectable> tenants;
String tenantsNoAlerts = tenants.stream()
.filter(entry -> !idTenantsWithAlerts.contains(entry.getId()))
.map(entry -> entry.getName())
.collect(Collectors.joining(", "));
英文:
You can filter the list by Id
, then map
, then collect
with a joining collector to reduce the Stream
to a String
.
List<Selectable> tenants;
String tenantsNoAlerts = tenants.stream()
.filter(entry -> !idTenantsWithAlerts.contains(entry.getId()))
.map(entry -> entry.getName())
.collect(Collectors.joining(", "));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论