如何明确地对数据进行分组?

时间:2013-12-09 10:17:54

标签: java jsp if-statement

我从特定类别的数据库中获取数据。 假设我选择或传递数据来查询该类别是否为Laptop,那么它会为我提供所有属性及其值的数据。 喜欢:

enter image description here

我在JSP页面上获取和显示数据的代码是:

<%
            List<String> attribNameList = (List<String>)request.getAttribute("attribName");
            List<String> attribValueList = (List<String>)request.getAttribute("attribValue");
            List<String> attribDataList = (List<String>)request.getAttribute("attribData");
            String aname,aval,adata;

            for(int i = 0 ; i<attribValueList.size() ; i++)
            {
                aname = attribNameList.get(i);
                aval = attribValueList.get(i);
                adata = attribDataList.get(i);

        %>
            <a><%=i%><%= aname %></a> &nbsp;
            <a><%= aval %></a> &nbsp;
            <%
                if(adata == null)
                {

                }
                else
                {
                    %>
                        <a><%= adata %></a>
                    <%
                }
            %>

            <br>
        <%
            }
        %> 

此处aname显示属性名称,即RAM, Processor, etc.

aval显示值,即4, 2.8, etc.

adata显示最后一个数据,即GB, GHz, MP, etc.

现在我想以类别的方式显示数据,就像首先显示所有内存属性一样。 喜欢:

RAM 4 GB
HDD 1 TB
Cache 3 MB, etc.

如何以这种格式显示数据? 我尝试使用if condition adata变量检查

if(adata.equals("GB")||adata.equals("TB")||adata.equals("MB"))
{
    //memory category data display
}
else
{
    //Other data
}

但它不起作用。

任何建议请......

1 个答案:

答案 0 :(得分:1)

如何创建自定义对象来存储条目:

class MyDataRow implements Comparable<MyDataRow> {
    private String aname;
    private String aval;
    private String adata;

    // getters, setters, constructors etc

    @Override
    public int compareTo(MyDataRow other) {
      final int BEFORE = -1;
      final int EQUAL = 0;
      final int AFTER = 1;

      if(other == null) return AFTER;
      if(other.getAdata().equals(this.adata)) return EQUALS;

      if(this.adata.equals("GB")||this.adata.equals("TB")||this.adata.equals("MB"))
      {
          if(other.getAdata().equals("GB") || xxxxxxx) return EQUAL;
          return BEFORE;
      }

      if(next category in the list... etc etc)
    }
}

然后,数据库查询的结果将填充List。在MyDataRow中,您可以使用所需的排序逻辑覆盖'compareTo'方法。在进入将列表打印到页面的循环之前,请调用Collections.sort(myDataRowList):

List<MyDataRow> myDataRowList = new ArrayList<MyDataRow>();
for(int i = 0 ; i<attribValueList.size() ; i++)
{
       aname = attribNameList.get(i);
       aval = attribValueList.get(i);
       adata = attribDataList.get(i);
       myDataRowList.add(new MyDataRow(aname, aval, adata);
}

Collections.sort(myDataRowList); // now your myDataRowList is sorted in the order you want

for(MyDataRow myDataRow : myDataRowList) {

    // print rows to screen

}