Home > OS >  Find all occurences of an Element in List
Find all occurences of an Element in List

Time:12-08

I want to write a method with the following body:

public static List<Integer> collectAllIndices(List<String> ls, String elem) {

        List<Integer> list = new ArrayList<>();

        return list;
    }

I have to save the Position(index) of every occurrence in a new List How can I do this? if I'm not wrong, indexof() only returns the first occurrence?

CodePudding user response:

With Java 8:

public static <T> List<Integer> collectAllIndices(List<T> list, T element) {
    List<Integer> results = IntStream.range(0, ls.size())
        .boxed()
        .filter(i -> list.get(i).equals(element))
        .collect(Collectors.toList());
    return results;
}

CodePudding user response:

You could simply iterate through the list and save them. Something like:

public static List<Integer> collectAllIndices(List<String> ls, String elem) {

        List<Integer> list = new ArrayList<>();

        for(int i = 0; i < ls.size(); i  ) {
            if(elem.equals(ls.get(i)) {
                list.add(i);
            }
        }

        return list;
}

EDIT: it seems like a commenter posted the same solution at the same time

CodePudding user response:

You can just iterate and increment an index counter, if the element in the list matches, store it in an index list. Also this looks like a generic piece of code, so you can use generic type <T>, and it will work with any type that support equals, not only strings.

Example:

public static <T> List<Integer> collectAllIndices(List<T> ls, T elem) {
    List<Integer> results = new ArrayList<>();
    int index = 0;
    for (var i : ls) {
        if (i.equals(elem)) {
            results.add(index);
        }
        index  ;
    }
    return results;
}
  •  Tags:  
  • java
  • Related