Compare First 3 Character String with List of String of Each String First 3 Character

后端 未结 5 1256

The Sample Code which needs a solution?

public class TestJJava {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

               


        
5条回答
  •  感情败类
    2021-01-26 07:26

    You aren't currently comparing the first three characters because subList doesn't actually apply a substring function (here it copies the list as is). You can also initialize your List more efficiently (and you should program to the List interface). I would stream() it and map each element using String.substring and anyMatch. Like,

    String abc = "123XXXXX0";
    List lstValues = new ArrayList<>(List.of("111XXXX1", "122XXX1", "123XXXX1"));
    if (lstValues.stream().map(x -> x.substring(0, 3)).anyMatch(abc.substring(0, 3)::equals)) {
        System.out.println("**** Match Found ***");
    } else {
        System.out.println("**** No Match Found ****");
    }
    

    Which outputs

    **** Match Found ***
    

提交回复
热议问题