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
}
Hasen
  • 11,710
  • 23
  • 77
  • 135
  • 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)? – Thomas Feb 26 '20 at 15:26
  • @Thomas I thought there would be a better way. Like you have `.contains` if the `ArrayList` is an array of primitives. – Hasen Feb 26 '20 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. – Thomas Feb 26 '20 at 15:44
  • @Thomas Yes, so I thought there must be some way to check only the deeper elements. Wishful thinking I guess. – Hasen Feb 26 '20 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). – Thomas Feb 26 '20 at 15:57
  • @Thomas Yes that's what I already did after your suggestion, certainly not long code as you say and it works fine of course. What I meant is I thought there would be something built in like `.contains`. – Hasen Feb 26 '20 at 15:59
  • Well, if there'd be something like that it would need to look like `indexOf(Predicate)`, e.g. like Apache Commons Collection's [ListUtils](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/ListUtils.html): `ListUtils.indexOf( grid, g -> g.numb == 12 )` – Thomas Feb 27 '20 at 07:43

1 Answers1

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);
zfChaos
  • 415
  • 4
  • 13