检查对象的列表数组中是否存在值

时间:2019-12-08 23:42:02

标签: java

你好,我在客户端输入y时循环

,然后我想获取您输入的值并确保它包含在我的客户列表中 但我不知道该怎么做

Scanner scanner = new Scanner( System.in );
ArrayList<Cliente> clientes = new ArrayList<Cliente>();
ArrayList<OrderService> orderService = new ArrayList<OrderService>();
System.out.println("add Cliente name")
string name = scanner.nextLine();
cliente.setName(name);
fazer um loop para se quiser adicionar mais clientes.

System.out.println("starting");

boolean value = true;
while(value)){
    System.out.println("Enter a new Client name");
    string name = scanner.nextLine();
    if(!name && name.trim().equals("")){
        Cliente cliente = new Cliente(name);
        clientes.add(cliente);
        System.out.println("Cliente "+cliente.getName+" Adicionado")
    }
    else{
        System.out.println("Nome invalido")
    }
    System.out.println("Do you want to add more client? Y for Yes, N for no");
    string response = scanner.nextLine(); 
    if(!response.equalsIgnoreCase(y)){
        value = false
    }
}

System.out.println("Enter a Client name that you want to create a work order.");
string clientName = scanner.nextLine();

3 个答案:

答案 0 :(得分:1)

尝试使用流。

public static Cliente findByName(Collection<Cliente> clientes, String name)
{
    return clientes.stream().filter(cliente -> name.equals(cliente.getName())).findFirst().orElse(null);
}

答案 1 :(得分:1)

您可以使用流api轻松实现您的问题 假设您的Cliente类具有name属性。根据您提供的注释,可以在第二个if语句中使用checkedCliente

if(!name && name.trim().equals("")){
    Cliente checkedCliente = clientes.stream()
                .filter(x -> name.equals(x.getName()))    // check name is there?
                .findAny()
                .orElse(null);

    if(checkedCliente == null){
        Cliente cliente = new Cliente(name);
        clientes.add(cliente);
        System.out.println("Cliente "+cliente.getName+" Adicionado")
    }
    else {
        System.out.println("Cliente " + cliente.getName() + "is already in the collection");

        // checkedCliente can be used for updates etc in here.
    }
}

答案 2 :(得分:0)

这是检查数组列表是否包含字符串的方法

{{1}}