【问题标题】:Sorting a list of maps within before this while loop runs out(Java)在此while循环用完之前对地图列表进行排序(Java)
【发布时间】:2011-05-15 03:40:33
【问题描述】:

进行了一次数据库调用,结果是一堆行,包含两个类型为 AB 的字符串列。例如(x_a, y_b), (x_a, y1_b), (x2_a,y_b)

我们的想法是提出一个映射列表,例如 {(x_a,{y_b,y1_b}), (x2_a,{y_b})},其中类型 A 的对象不重复,并在从数据库中提取结果的同时执行此操作。

这是我尝试过的:

int i =0;
            List<String> type2 = new ArrayList<String>();
            Map<String,List<String>> type1_type2 = new HashMap<String,List<String>>();
            List<Map> list_type1_type2 = new ArrayList<Map>();

            String [] type1Array = new String[100];
            String [] type2Array = new String[100];
            int trackStart = 0;
while (res.next()){


                String type1 = res.getString(1);
                String type2 = res.getString(2);
                type1Array[i]=type1;
                type2Array[i] = type2;


                if(i>0 && !type1Array[i].equals(type2Array[i-1])){
                    int trackStop = i;
                    for(int j = trackStart; j<trackStop;j++){
                        type2.add(type2Array[j]);
                    }
                    type1_type2.put(type1Array[i-1], type2);
                    list_type1_type2.add(type1_type2);

                //debugging stuff   
                 String x = list_type1_type2.toString();
         System.out.println(x);
System.out.println(" printing because "+ type1Array[i]+" is not equal to " + type1Array[i-1]);
        type2 = new ArrayList<String>();
     type1_type2 = new HashMap<String,List<String>>();
                     trackStart=i;
                     }

                     i++;


                }

当结果对象的最后一个type1值相同时,此方法不起作用。

有没有办法以同样的精神(在 while(res.next) 内)做到这一点,而无需先将数据库调用的结果存储在单独的数组中,或者在 while 循环之外添加一个额外的 for 循环来“修补它起来”?

【问题讨论】:

  • Ugg 真的很难阅读代码。我会认真考虑重构以避免使用 field1、field2 等类型的变量命名。这让事情真的很难理解。其次,您是否考虑过使用集合类而不是数组是否可以更好地编写代码?它通常会使事情变得简单得多。
  • 只是一个提示:当你必须嵌套 Collection 类时,这通常表明你应该创建一个新类来包含所有内容,否则组织行为将变得非常乏味并且会犯愚蠢的错误。

标签: java database arrays data-structures hashmap


【解决方案1】:

执行此操作的简单方法是使用 Guava / Google Collections SetMultiMap。这本质上是从键(您的“A”对象)到一组值(您的“B”对象)的映射。

[我不会尝试为你编写代码。你当前的代码太难读了……除非你付钱给我:-)]

但是,更好的办法是让数据库进行排序。如果您能做到这一点,您将减少通过数据库连接发送的(冗余)数据量……假设您使用的是 JDBC。

【讨论】:

  • 大声笑...我当然不希望您编写代码...这很难作为草稿输入...谢谢我会研究番石榴..有点清理/修补我的代码的工作......只是想知道是否有一个根本不同的解决方案......
【解决方案2】:

如果您不想像 {x_a:[y_b, y_b]} 这样重复,请使用集合作为地图的值:

Map<String,Set<String>> type1_type2;

我不知道其他各种列表和数组的用途。您可能只需使用 type1_type2 地图即可。用伪代码处理每个 (x, y):

Set s = type1_type2.get(x)
if s == null:
    s = new Set()
    type1_type2.put(x, s)
s.add(y)

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多