0

I want to find if the property numb in the ArrayList grids contains a certain value or not. Then I want to get the index of the entry that contains that value.

public class Grid {
  public int numb;

  public GridSeg(int numb) {
    this.numb = numb;
  }
}

public ArrayList<Grid> grids = new ArrayList<Grid>();

for (int i = 0; i < 6; i++) {
  Grid grid = new Grid(i);
  grids.add(grid);
}

/pseudo code since I don't know how it is done
if (grids.numb.contains(12)) {
  if (grid.numb == 12) //get grid index
}
7
  • 4
    What exactly are you struggling with? Why not just use an index based for-loop, check the numb property of the current element and if it matches return the current index (and of course return -1 or something similar if no such element has been found)? Commented Feb 26, 2020 at 15:26
  • @Thomas I thought there would be a better way. Like you have .contains if the ArrayList is an array of primitives. Commented Feb 26, 2020 at 15:31
  • Well, list.contains() tells you whether an element is contained in the list (as defined by equals()) but it doesn't tell you where. Commented Feb 26, 2020 at 15:44
  • @Thomas Yes, so I thought there must be some way to check only the deeper elements. Wishful thinking I guess. Commented Feb 26, 2020 at 15:47
  • Well something like for(int i; i < list.size(); i++) { if(list.get(i).numb == 12) return i; } return -1; isn't that much code (or something like int index = 0; for( Grid g : list) { if( g.numb == 12) return index; index++; } return -1; if you want to use a foreach). Commented Feb 26, 2020 at 15:57

1 Answer 1

2

You can achieve it with streams

    ArrayList<Grid> grids = new ArrayList<>();
    Grid grid = grids.stream().filter(l -> l.numb == 12).findFirst().orElse(null);
    int index = grids.indexOf(grid);
Sign up to request clarification or add additional context in comments.

2 Comments

This solution iterates twice the list, first for filtering, then for getting the index of the object.
Interesting answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.