Home > Enterprise >  Find and print a string using a piece of other string
Find and print a string using a piece of other string

Time:02-24

I have the following code

    ArrayList<String> proposta = new ArrayList<String>();
    String propostaString = "";
    proposta.add("213141441414");
    proposta.add("515151551");
    proposta.add("2626262662");
    proposta.add("26262627373");
    proposta.add("7373632525");
    proposta.add("1515252");
    proposta.add("262636474");
    proposta.add("11414142222");
    String entrada = proposta.toString();
    
    String lastDigitsClient = "2222";
    String lastFour = "2222";
    boolean Equal = false;
    if(lastDigitsClient.contains(lastFour)) {
        Equal=true;
        System.out.println("ULTIMOS DIGITOS : TRUE = "  Equal);
        System.out.println("Lista de Propostas: "  entrada);

    }

I want to print the proposta 11414142222 using the value of lastDigitsClient, how could I do it?

CodePudding user response:

For a simple approach, I would expect something more like:

ArrayList<String> proposta = new ArrayList<String>();
proposta.add("213141441414");
proposta.add("515151551");
proposta.add("2626262662");
proposta.add("26262627373");
proposta.add("7373632525");
proposta.add("1515252");
proposta.add("262636474");
proposta.add("11414142222");

String match = "";
boolean matchFound = false;

String lastFour = "2222";
for(String s : proposta) {
  if(s.endsWith(lastFour)) {
    match = s;
    matchFound = true;
    break;
  }
}

if (matchFound) {
  System.out.println("match = "   match);
}
else {
  System.out.println("No match found.");
}

CodePudding user response:

You can use .filter() to get all values in a list that match a condition

final String lastFour = "2222";
System.out.println("Lista de Propostas: "   proposta);
Optional<String> opt = proposta.stream().filter(s -> s.endsWith(lastFour)).findFirst();
if (opt.isPresent()) {
  System.out.println("ULTIMOS DIGITOS : TRUE");
}

CodePudding user response:

You can use streams API

List<String> strings = Arrays.asList(
        "213141441414",
        "515151551",
        "2626262662",
        "26262627373",
        "7373632525",
        "1515252",
        "262636474",
        "11414142222"
);
String lastFour = "2222";
strings.stream().filter(s -> s.endsWith(lastFour)).forEach(System.out::println);
  •  Tags:  
  • java
  • Related