Java find all indexes

Java – Find all indexes of a value in a List

I’m trying to search an ArrayList for a user input. I’ve managed to create a search that prints the index of the first occurrence from within the list.

I’m having trouble trying to get the rest of the indexes that the item are stored.

Here is the code I have got so far to print the first index of search :

I understand that a loop needs to be added. But I am having trouble trying to formulate it.

Example

ArrayList names = new ArrayList(); names.add("Bob"); names.add("Jerry"); names.add("Bob"); names.add("Mick"); 

Say search = «Bob» . My expected result would be . Instead, I am only able to get the index of the first occurrence ( 0 ).

assert allIndexesOf(names, "Bob").equals(List.of(0, 2)); [. ] private List allIndexesOf(List list, Object o) < // How can this be implemented? >

How can I get all indexes that match the search string?

Best Solution

Explanation

The method List#indexOf only returns the index of the first found matching element. From its documentation:

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. [. ]

But you want all, therefore you also need to iterate all elements.

Also note that calling List#contains is not necessary since List#indexOf also answers this question, it returns -1 if not found. In fact in an ArrayList both calls are very expensive (they iterate from left to right until found) so you shouldn’t use unnecessary statements if they are such expensive.

Solution

Instead just iterate all elements and collect the ones that match:

ArrayList author = . String needle = . // Collect matches List matchingIndices = new ArrayList<>(); for (int i = 0; i < author.size(); i++) < String element = author.get(i); if (needle.equals(element)) < matchingIndices.add(i); >> // Print matches matchingIndices.forEach(System.out::println); 

Or you may use some of the very convenient methods of the Stream API. Stream#filter (documentation) for example:

List matchingIndices = IntStream.range(0, author.size()) .filter(i -> needle.equals(author.get(i))) // Only keep those indices .collect(Collectors.toList()); 
Java – Is Java “pass-by-reference” or “pass-by-value”

Java is always pass-by-value. Unfortunately, when we deal with objects we are really dealing with object-handles called references which are passed-by-value as well. This terminology and semantics easily confuse many beginners.

public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; // we pass the object to foo foo(aDog); // aDog variable is still pointing to the "Max" dog when foo(. ) returns aDog.getName().equals("Max"); // true aDog.getName().equals("Fifi"); // false aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // change d inside of foo() to point to a new Dog instance "Fifi" d = new Dog("Fifi"); d.getName().equals("Fifi"); // true >

In the example above aDog.getName() will still return «Max» . The value aDog within main is not changed in the function foo with the Dog «Fifi» as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return «Fifi» after the call to foo .

public static void main(String[] args) < Dog aDog = new Dog("Max"); Dog oldDog = aDog; foo(aDog); // when foo(. ) returns, the name of the dog has been changed to "Fifi" aDog.getName().equals("Fifi"); // true // but it is still the same dog: aDog == oldDog; // true >public static void foo(Dog d) < d.getName().equals("Max"); // true // this changes the name of d to be "Fifi" d.setName("Fifi"); >

In the above example, Fifi is the dog’s name after call to foo(aDog) because the object’s name was set inside of foo(. ) . Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog , but it is not possible to change the value of the variable aDog itself.

For more information on pass by reference and pass by value, consult the following SO answer: https://stackoverflow.com/a/430958/6005228. This explains more thoroughly the semantics and history behind the two and also explains why Java and many other modern languages appear to do both in certain cases.

Python – How to check if a list is empty
if not a: print("List is empty") 

Using the implicit booleanness of the empty list is quite pythonic.

Источник

Find all indexes of a value in a List [duplicate]

Demo Now, if you want to get the list of indices for , you can do so as follows: The indexOf() method of List interface returns the index of the first occurrence of the specified element in this list. Solution 1: Explanation The method only returns the index of the first found matching element.

Find all indexes of a value in a List [duplicate]

I’m trying to search an ArrayList for a user input. I’ve managed to create a search that prints the index of the first occurrence from within the list.

I’m having trouble trying to get the rest of the indexes that the item are stored.

Here is the code I have got so far to print the first index of search :

I understand that a loop needs to be added. But I am having trouble trying to formulate it.

Example
ArrayList names = new ArrayList(); names.add("Bob"); names.add("Jerry"); names.add("Bob"); names.add("Mick"); 

Say search = «Bob» . My expected result would be . Instead, I am only able to get the index of the first occurrence ( 0 ).

assert allIndexesOf(names, "Bob").equals(List.of(0, 2)); [. ] private List allIndexesOf(List list, Object o) < // How can this be implemented? >

How can I get all indexes that match the search string?

Explanation

The method List#indexOf only returns the index of the first found matching element. From its documentation:

Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. [. ]

But you want all , therefore you also need to iterate all elements .

Also note that calling List#contains is not necessary since List#indexOf also answers this question, it returns -1 if not found. In fact in an ArrayList both calls are very expensive (they iterate from left to right until found) so you shouldn’t use unnecessary statements if they are such expensive.

Solution

Instead just iterate all elements and collect the ones that match:

ArrayList author = . String needle = . // Collect matches List matchingIndices = new ArrayList<>(); for (int i = 0; i < author.size(); i++) < String element = author.get(i); if (needle.equals(element)) < matchingIndices.add(i); >> // Print matches matchingIndices.forEach(System.out::println); 

Or you may use some of the very convenient methods of the Stream API . Stream#filter (documentation) for example:

List matchingIndices = IntStream.range(0, author.size()) .filter(i -> needle.equals(author.get(i))) // Only keep those indices .collect(Collectors.toList()); 

You could go over the entire list and save all the indexes that match the search term. Java 8’s steams give you a pretty elegant way of doing this:

int[] indexes = IntStream.range(0, names.size()) .filter(i -> names.get(i).equals(search)) .toArray(); 

Java — Find all indexes of a value in a List, The method List#indexOf only returns the index of the first found matching element. From its documentation: Returns the index of the first occurrence of the specified element in this list, or -1 if this list does not contain the element. [] But you want all, therefore you also need to iterate all elements. Code sampleList matchingIndices = IntStream.range(0, author.size()).filter(i -> needle.equals(author.get(i))) // Only keep those indices.collect(Collectors.toList());Feedback

How to get the index of object by its property in Java list

I would like to get the index of an object in a list by its property in Java.
Example:

List list = new ArrayList<>(); list.add(new MyObj("Ram"); list.add(new MyObj("Girish"); list.add(new MyObj("Ajith"); list.add(new MyObj("Sai"); public class MyObj < public String name; public MyObj(String name)< this.name=name; >> 

Now, I would like to the get the index of an Object which contains the name as «Girish». Please do let me know the code in JAVA.

If you want a solution with stream use this one:

int index = IntStream.range(0, list.size()) .filter(i -> list.get(i).name.equals(searchName)) .findFirst() .orElse(-1); 

In case you have a List , all you can do is to iterate over each element and check required property. This is O(n) .

public static int getIndexOf(List list, String name) < int pos = 0; for(MyObj myObj : list) < if(name.equalsIgnoreCase(myObj.name)) return pos; pos++; >return -1; > 

In case you want to increase performance. Then you could implement your own data structure. Note, that key feature is that your key property should be a key of a HashMap and value of HashMap should be index. Then you get O(1) performance.

public static final class IndexList extends AbstractList  < private final MapindexObj = new HashMap<>(); private final Map keyIndex = new HashMap<>(); private final Function getKey; public IndexList(Function getKey) < this.getKey = getKey; >public int getIndexByKey(String key) < return keyIndex.get(key); >@Override public int size() < return keyIndex.size(); >@Override public boolean add(E e) < String key = getKey.apply(e); if (keyIndex.containsKey(key)) throw new IllegalArgumentException("Key '" + key + "' duplication"); int index = size(); keyIndex.put(key, index); indexObj.put(index, e); return true; >@Override public E get(int index) < return indexObj.get(index); >> 
IndexList list = new IndexList<>(myObj -> myObj.name); list.add(new MyObj("Ram")); list.add(new MyObj("Girish")); list.add(new MyObj("Ajith")); list.add(new MyObj("Sai")); System.out.println(list.getIndexByKey("Ajith")); // 2 

indexOf() will work if you change the .equals function

I’d suggest just iterating through

int getIndex(String wanted) < for(int i = 0; i> > 

indexOf() will return the index of the first occurrence of a value. For example:

int myIndex = list.indexOf(«Ram»)

(Note though that your arraylist doesn’t contain «Ram», it contains an object of type MyObj with a name of «Ram»)

Bear in mind ArrayLists start at 0 not one.

How to get the index of object by its property in Java list, indexOf () will return the index of the first occurrence of a value. For example: int myIndex = list.indexOf («Ram») (Note though that your arraylist doesn’t contain «Ram», it contains an object of type MyObj with a name of «Ram») Bear in mind ArrayLists start at 0 not one. Share.

Find all the indexes of an item within a list using stream API

I am trying sequential search using Java 8 streams and lambda expressions. Here is my code

List list = Arrays.asList(10, 6, 16, 46, 5, 16, 7); int search = 16; list.stream().filter(p -> p == search).forEachOrdered(e -> System.out.println(list.indexOf(e))); 

I know list.indexOf(e) always prints the index of the first occurrence. How do I print all the indexes?

For a start, using Lambdas is not the solution to all problems. but, even then, as a for loop, you would write it:

List results = new ArrayList<>(); for (int i = 0; i < list.size(); i++) < if (search == list.get(i).intValue()) < // found value at index i results.add(i); >> 

Now, there’s nothing particularly wrong with that, but note that the critical aspect here is the index, not the value. The index is the input, and the output of the ‘loop’.

List list = Arrays.asList(10, 6, 16, 46, 5, 16, 7); int search = 16; int[] indices = IntStream.range(0, list.size()) .filter(i -> list.get(i) == search) .toArray(); System.out.printf("Found %d at indices %s%n", search, Arrays.toString(indices)); 

To find the indexes of every value in a List as a Map , we can use an IntStream of indexes with Collectors.groupingBy .

import java.util.stream.Collectors; import java.util.stream.IntStream; //. final Map> indexMap = IntStream.range(0, list.size()).boxed() .collect(Collectors.groupingBy(list::get)); // <16=[2, 5], 5=[4], 6=[1], 7=[6], 10=[0], 46=[3]>//Map of item value to List of indices at which it occurs in the original List 

Now, if you want to get the list of indices for search , you can do so as follows:

System.out.println(indexMap.get(search)); 

Java — Find all the indexes of an item within a list using, Add a comment. 1. To find the indexes of every value in a List as a Map, we can use an IntStream of indexes with Collectors.groupingBy. import java.util.stream.Collectors; import java.util.stream.IntStream; // final Map> indexMap = IntStream.range (0, list.size ()).boxed () .collect …

Java List indexOf() Method

The indexOf() method of List interface returns the index of the first occurrence of the specified element in this list. It returns -1 if the specified element is not present in this list.

Syntax

public int indexOf(Object o)

Parameters

The parameter ‘o’ represents the element to be searched.

Throws:

ClassCastException — If the type of the specified element is not compatible with this list.

NullPointerException — If the specified element is null and this list does not allow null elements.

Return

The indexOf() method returns the index of the first occurrence of the specified element if it is present in this list, else it returns -1.

Example 1

import java.util.LinkedList; import java.util.List; public class JavaListIndexOfExample1 < public static void main(String[] args) < Listlist= new LinkedList<>(); for (int i=0;i <6;i++)< list.add(i); // returns the element at the specified position in this list int value =list.indexOf(i); System.out.println("Element stored at index "+i+" : "+value); >> >
Element stored at index 0 : 0 Element stored at index 1 : 1 Element stored at index 2 : 2 Element stored at index 3 : 3 Element stored at index 4 : 4 Element stored at index 5 : 5

Example 2

import java.util.LinkedList; import java.util.List; public class JavaListIndexOfExample2 < public static void main(String[] args) < Listlist= new LinkedList<>(); list.add(null); list.add(null); list.add(null); // returns -1 if the no value is present in the specified index int value =list.indexOf(90); System.out.println("Element stored at Index "+90+" : "+value); > >
Element stored at Index 90 : -1

Example 3

import java.util.LinkedList; import java.util.List; public class JavaListIndexOfExample3 < public static void main(String[] args) < Listlist= new LinkedList<>(); list.add(67); list.add(89); // returns -1 if the no value is present in the specified index int value =list.indexOf(null); System.out.println("Element stored at "+null+" : "+value); > >
Element stored at null : -1

Java List indexOf() Method with Examples, Parameters. The parameter ‘o’ represents the element to be searched. Throws: ClassCastException- If the type of the specified element is not compatible with this list.. NullPointerException- If the specified element is null and this list does not allow null elements.. Return. The indexOf() method returns the index of the first …

Источник

Читайте также:  $TI
Оцените статью