Search code examples
javaarraylistcollections

Best way to construct an object class with a collection array of three elements


I was thinking about making in Java a collection class of an array with three elements: object , string, boolean like in the way I can use in a loop like:

for ( objectArray collectionElement  : ArrayElementsCollection ) {
   if ( collectionElement.String == 'type_of_element' && collectionElement.boolean ) {
      // doing what I need with collectionElement.Object
   }
}

What would be the best way to implement it? Using an ArrayList<ArrayList<ArrayList>>? A map?

EDIT Aug 15, 2023

Thanks to @tgdavies , I figured simplest way to manage my list which was a collection of active interfaces based on @tgdavies sample, I made:

class myConnections {
    public String connectionName;
    public int connectionType;
    public Boolean connectionState;
    public String connectionAddress;

    .....
}

public class MainCustomClass() {
    
    private customConnections(){ collectionConnections = new ArrayList<myConnections>(); }
        
    public void getActiveConnections() {
        customConnections.clear();

        if (!localIPs.isEmpty() && localIPs.size() > 0) {
            IntStream.range(0, localIPs.size())
                .forEach(i -> customConnections.add(new myConnections(localHostnames.get(i), connectionType, connectionState, localIPs.get(i))));
        }
    }
}

so it worked for my scopes. Thanks again @tgdavies!


Solution

  • You just need a List of a class with three fields (in real life, write getters, I've omitted them for simplicity):

    class Record {
      public String string;
      public boolean bool;
      public Object object;
    }
    

    Then your code becomes:

    List<Record> records = ...
    for ( Record record: records) {
       if ( record.string.equals("type_of_element") && record.bool ) {
          // doing what I need with record.object
       }
    }
    

    This answer assumes that you might have many records which match. If you want to go directly to a single record which has a string element of "type_of_element" and a bool which is true, you could also use nested Maps:

    Map<String,Map<Boolean,Object>> records = ...
    Map<Boolean,Object> boolMap = records.get("type_of_element");
    if (boolMap!= null) {
      Object obj = boolMap.get(true);
      if (obj != null) {
        // do your stuff on obj
      }
    }