Список фильтрации с использованием потоков Java8 - PullRequest
0 голосов
/ 25 мая 2020

У меня есть следующий список объектов клиентов:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class CheckForResource {

    public static void main(String[] args) {
        Customer john = new Customer("111", "P_1", "daily",
                "create", "table_1", "03-05-2020",
                "03-05-2020", "140");

        Customer mary = new Customer("111", "P_1", "daily",
                "delete", "table_1", "03-05-2020",
                "03-05-2020", "30");

        Customer joseph = new Customer("222", "P_2", "weekly",
                "create", "table_2", "03-05-2020",
                "03-05-2020", "50");

        Customer jason = new Customer("222", "P_2", "daily",
                "update", "table_2", "03-05-2020",
                "03-05-2020", "40");

        Customer mario = new Customer("111", "P_1", "weekly",
                "create", "table_1", "03-05-2020",
                "03-05-2020", "20");

        Customer danny = new Customer("111", "P_1", "monthly",
                "update", "table_1", "03-05-2020",
                "03-05-2020", "100");

        List<CheckForResource.Customer> customers = Arrays.asList(john, mary, joseph, jason, mario, danny);

    }


    public static class Customer {

        final String Id;
        final String pCode;
        final String usageType;
        final String operation;
        final String resource; 
        final String startTime;
        final String endTime;
        final String value;

        public Customer(String id, String pCode, String usageType, String operation,
                        String resource, String startTime, String endTime, String value) {
            Id = id;
            this.pCode = pCode;
            this.usageType = usageType;
            this.operation = operation;
            this.resource = resource;
            this.startTime = startTime;
            this.endTime = endTime;
            this.value = value;
        }
    }
}

Я хочу вернуть истину, если в списке есть хотя бы 1 запись каждого из следующих пунктов

  1. customerId = "111", operation = "create", usageType = "daily"
  2. customerId = "111", operation = "create", usageType = "ежемесячно"
  3. customerId = "111" , operation = "delete", usageType = "daily"
  4. customerId = "111", operation = "delete", usageType = "month"
  5. customerId = "111", operation = " update ", usageType =" daily "
  6. customerId =" 111 ", operation =" update ", usageType =" month "

Как добиться этого с помощью Steam?

Ответы [ 2 ]

1 голос
/ 25 мая 2020

Вы можете использовать .anyMatch()

Predicate<Customer> p = c -> c.getId().equals("111") &&
                        (c.getUsageType().equals("daily") || c.getUsageType().equals("monthly")) &&
                        (c.getOperation().equals("create") || c.getOperation().equals("delete") || c.getOperation().equals("update"));
boolean result = customers.stream().filter(p)
                          .map(c -> c.getId().concat(c.getOperation()).concat(c.getUsageType()))  // Map to create hash string for detect unique
                          .distinct().count() == 6;  // distinct and check the count.
0 голосов
/ 25 мая 2020

Попробуйте это так:

  • у вас есть шесть разных возможностей после фильтрации id == 111.
  • Итак, если вы создаете список предикатов, вы можете сделать следующее
  • если у вас шесть записей, то это удовлетворяет условию.

Создайте список предикатов на основе operation и usageType

List<Predicate<String>> preds = toPredicateList(
        new String[] { "create", "delete", "update" },
        new String[] { "daily", "monthly"});

Определить если условия соблюдены.

boolean result = 
        customers
            .stream()
            .filter(c -> c.Id.equals("111"))
            .map(c -> c.operation + c.usageType)
            .filter(preds.stream().reduce(k -> false,
                                Predicate::or))
            .collect(Collectors.toSet()).size() == 6;

System.out.println(result);

Составить список предикатов

public List<Predicate<String>> toPredicateList(String[] ops,
            String[] types) {

        List<Predicate<String>> list = new ArrayList<>();
        for (String o : ops) {
            for (String t : types) {
                list.add(s -> s.equals(o + t));
            }
        }
    }
    return list;
}

...