简体   繁体   中英

Compare all values of arraylist to a string

I have an array list abc which has certain values -

ArrayList< String > abc = new ArrayList<>();
abc.add("hi");
abc.add("hello Yash");
abc.add("i am Yash");
String x = "Yash";

Now, I want to know if x is contained in any of the elements of abc .
If it is, then get the index of the elements which contain x .

Here is a simple solution:

public class FindText
{


    public static void main(String[] args)
    {
        ArrayList< String > abc = new ArrayList<>();
        abc.add("hi");
        abc.add("hello Yash");
        abc.add("i am Yash");
        String x = "Yash";

        for(int i=0; i<abc.size(); i++)
        {
            if(abc.get(i).contains(x))
            {
                int index = i;
                System.out.println(index);
            }
        }
    }
}

It gives you 1 and 2 as indexes which includes the text "Yash"

You can achieve this in 2 different ways...

  1. The old school
  2. and the lambdas way

Old school Example:

public static void main(String[] args) {
    List<String> abc = new ArrayList<>();
    abc.add("hi");
    abc.add("hello Yash");
    abc.add("i am Yash");
    String x = "Yash";
    List<String> resultOldSchool = new ArrayList<>();
    for (String sentence : abc) {
        if (sentence.contains(x)) {
            resultOldSchool.add(sentence);
        }
    }
    System.out.println(resultOldSchool);
}

Lambdas way Example:

public static void main(String[] args) {
    List<String> abc = new ArrayList<>();
    abc.add("hi");
    abc.add("hello Yash");
    abc.add("i am Yash");
    String x = "Yash";
    List<String> resultJava8 = findStringInList(abc, x);
    if (!resultJava8.isEmpty()) {
        System.out.println(resultJava8);
    }
}

public static List<String> findStringInList(final List<String> list, final String strng) {
    return list.stream().filter(s -> s.contains(strng)).collect(Collectors.toList());
}

feel free to decide....

Assuming that abc is a List<String> and x is a String then this should do the trick.

List<Integer> indexes = new LinkedList<Integer>();
for(int i = 0; i < abc.size(); i++)
{
    if(abc.get(i).contains(x))
         indexes.add(i);
}

After the loop finishes all the indexes of the elements that contain x will be in the indexes list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM