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

后端 未结 12 1057
长发绾君心
长发绾君心 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 09:10

    Yes!! Its possible. But you have to do some crooked work.

    1. Create a inner class with required variables. Eg: here am going to use 2 variables.( TNAME and TABTYPE).

       public class storeTables {
              private String tablename = "";
              private String tabletype = "";
              public storeTables(String a, String b)
              {
                  this.setTablename(a);
                  this.setTabletype(b);
              }
              public void setTablename(String tablename) {
                  this.tablename = tablename;
              }
              public String getTablename() {
                  return tablename;
              }
              public void setTabletype(String tabletype) {
                  this.tabletype = tabletype;
              }
              public String getTabletype() {
                  return tabletype;
              }}
      
    2. Create a List of the inner class created above and dont forget to encapsulate it.

      private List objlist= new ArrayList();
      
    3. Get the value stored to the list as a inner class object.

      String Query="SELECT * FROM TAB";
      while(rs.next())
      {
      String tname=rs.getString("TNAME");
      String tabtype=rs.getString("TABTYPE");
      getObjlist().add(new storeTables(tname,tabtype));
              }
      
    4. create a DATAMODEL and push the list to the datamodel

      private DataModel selectableItems= new ListDataModel(objlist);
      
    5. get the warpped data to another list.

      List items= (List)selectableItems.getWrappedData();
      
    6. Finally!!! printing the data.

      for(storeTables item:items){
      System.out.println(item.getTablename());
          }
      

    TADA !!!! it will print only the tablename and not the tabtype ;) Believe that there is nothing impossible in java Any doubts!!

提交回复
热议问题