How to get a list of specific fields values from objects stored in a list?

后端 未结 12 1221
长发绾君心
长发绾君心 2021-01-31 08:23

Say I have an list of objects with two fields field1 and field2, both of String type.

How do I get a list of all field1 values wit

12条回答
  •  耶瑟儿~
    2021-01-31 09:06

    Depends...

    ... whether your questions refers to avoiding iterating over the collection either:

    • in terms of ease of implementation at call points
    • or in terms of the algorithmic complexity.

    Concretely, do you mean:

    • you don't want to type in an iterating construct yourself (simply use a convenience library),
    • or you actually want something that would return elements auto-magically in O(1) without needing to process them (and have perfect access)?

    See below for solutions and options.


    Using Convenience Libraries

    If it's the first one, then look at Google Guava, LambdaJ, FunctionalJava or other libraries that implement basic functional constructs and will allow you to do what you want in a few expressive calls. But keep in mind these do what is says on the tin: they will filter, collect or transform a collection, and will iterate through its elements to do this.

    For instance:

    • Google Guava:

      Set strings = buildSetStrings();  
      Collection filteredStrings =
          Collections2.filter(strings, Predicates.containsPattern("^J"));  
      
    • Functional Java:

      Array a = array(97, 44, 67, 3, 22, 90, 1, 77, 98, 1078, 6, 64, 6, 79, 42);
      Array b = a.filter(even);
      
    • LambdaJ:

      List biggerThan3 = filter(greaterThan(3), asList(1, 2, 3, 4, 5));
      

    Perfect Access

    If it's the second one, this is not possible as-is, except if you architectured everything from the start so that your objects should be managed by a custom collection class that would indexing your objects based on their field values on insertion.

    It would keep them in buckets indexed by said value to be readily available for you to retrieve them as a list or set on demand.

    As mentioned in the comments below dounyy's answer, designing such a custom collection would probably have an impact on the API of the elements it would accept (most likely by defining a super interface to use for element types), or would require a fairly intricate implementation to resolve members dynamically (most likely by using reflection), if you ever wanted this collection to be generic.

提交回复
热议问题