Java 8 Stream按键筛选对象列表。排除列表中存在的键并获取字符串。

huangapple go评论70阅读模式
英文:

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.&quot; Care, Safe&quot;

Example:

public interface Selectable {
Long getId();
String getName();
}

I have a list&lt;Selectable&gt; tenants

id, name
34, &quot;House&quot;
35, &quot;Care&quot;
36, &quot;Villa&quot;
37, &quot;Safe&quot;

and another List&lt;Long&gt; idTenantsWithAlerts

id
34
36

I need the result String tenantsNoAlerts to be &quot;Care, Safe&quot;

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&lt;Selectable&gt; tenants;
String tenantsNoAlerts = tenants.stream()
    .filter(entry -&gt; !idTenantsWithAlerts.contains(entry.getId()))
    .map(entry -&gt; entry.getName())
    .collect(Collectors.joining(&quot;, &quot;));

huangapple
  • 本文由 发表于 2020年10月15日 15:24:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64366722.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定