2

I am fairly new to Java and I have stumbled across a problem I cannot figure out for the life of me. First let me explain what I am trying to do then I will show you the code I have so far.

I have a webservice that returns an array of arrays(which include company and lines of business strings). I wish to transform this into a string list, which I did in the first line of code below. Then I wish to Iterate through the list and every I come across a different value for company, I want to create a new ArrayList and add the associated line of business to the new list. Example output of webservice: 80,80,64,64 (this is presorted so the same companies will always be grouped together) the associated lobs would be 1,2,3,4 respectively. What I want: arraylist[0]: 1,2 arrayList[1]: 3,4

What I have so far:

    List coList = Arrays.asList(coArray);
    //create list of lists
    List<List<String>> listOfLists = new ArrayList<List<String>>();
    String cmp = "";
    for (int i=0;i<coList.size();i++){//loop over coList and find diff in companies
        String currentCo = ((__LOBList)coList.get(i)).getCompany();
        String currentLob = ((__LOBList)coList.get(i)).getLobNum();
        if(i<coArray.length-1){
            String nextCo = ((__LOBList)coList.get(i+1)).getCompany();
            if((currentCo.equals(nextCo))){
                //do nothing companies are equal
            }else{
                log("NOT EQUAL"); //insert logic to create a new array??
                ArrayList<String> newList = new ArrayList<String>();
        //      for(int j=0;j<coList.size();j++){
                newList.add( ((__LOBList)coList.get(i)).getLobNum());                   
        //      }   


                for(int k=0; k<listOfLists.size();k++){//loop over all lists
                    for(int l=0;l<listOfLists.get(k).size();l++){ //get first list and loop through

                    }
                    listOfLists.add(newList);   
                }

            }
        }


    }

My problem here is that it is not adding the elements to the new string array. It does correctly loop through coList and I put a log where the companies are not equal so I do know where I need to create a new arrayList but I cannot get it to work for the life of me, please help!

4

6 回答 6

1

创建一个Map<String, List<Bussiness>>

每次检索公司名称时,首先检查该键是否已在映射中。如果是,则检索列表并将Bussiness对象添加到其中。如果不是,则在空列表时插入新值并插入正在评估的值。

于 2013-06-11T20:18:33.133 回答
1

是的,你可以这样做,但是用 Java 编写真的很烦人。注意:在 Clojure 或 Haskell 等函数式编程语言中,这简直是脑残。它只是一个名为group-by. 在java中,我会这样做:

  1. 初始化列表列表。
  2. 创建一个last作为 List 的指针。这包含您添加到的最后一个列表。
  3. 只要“没有任何变化”,迭代原始数据并填充到最后。如果发生了变化,请创建一个新的last.

我会告诉你如何:

package com.sandbox;

import java.util.ArrayList;
import java.util.List;

public class Sandbox {

    public static void main(String[] args) {
        ArrayList<String> rawInput = new ArrayList<String>();
        rawInput.add("80");
        rawInput.add("80");
        rawInput.add("60");
        rawInput.add("60");
        new Sandbox().groupBy(rawInput);
    }

    public void groupBy(List<String> rawInput) {
        List<List<String>> output = new ArrayList<>();
        List<String> last = null;

        for (String field : rawInput) {
            if (last == null || !last.get(0).equals(field)) {
                last = new ArrayList<String>();
                last.add(field);
                output.add(last);
            } else {
                last.add(field);
            }
        }

        for (List<String> strings : output) {
            System.out.println(strings);
        }
    }
}

这输出:

[80, 80]
[60, 60]

当然,你可以按照其他人的建议去做,但这会改变你的数据类型。他们建议“适合这项工作的工具”,但他们没有提到番石榴的Multimap。如果您决定将数据类型更改为地图,这将使您的生活更轻松。

这是本文中如何使用它的示例:

public class MutliMapTest {
    public static void main(String... args) {
  Multimap<String, String> myMultimap = ArrayListMultimap.create();

  // Adding some key/value
  myMultimap.put("Fruits", "Bannana");
  myMultimap.put("Fruits", "Apple");
  myMultimap.put("Fruits", "Pear");
  myMultimap.put("Vegetables", "Carrot");

  // Getting the size
  int size = myMultimap.size();
  System.out.println(size);  // 4

  // Getting values
  Collection<string> fruits = myMultimap.get("Fruits");
  System.out.println(fruits); // [Bannana, Apple, Pear]

  Collection<string> vegetables = myMultimap.get("Vegetables");
  System.out.println(vegetables); // [Carrot]

  // Iterating over entire Mutlimap
  for(String value : myMultimap.values()) {
   System.out.println(value);
  }

  // Removing a single value
  myMultimap.remove("Fruits","Pear");
  System.out.println(myMultimap.get("Fruits")); // [Bannana, Pear]

  // Remove all values for a key
  myMultimap.removeAll("Fruits");
  System.out.println(myMultimap.get("Fruits")); // [] (Empty Collection!)
 }
}
于 2013-06-11T20:19:32.183 回答
1

在我看来,更好的选择是列表地图。让公司 ID 作为 Map 中的键,并将该公司 ID 的每个新项目附加到作为值的列表中。

为工作使用正确的工具。数组级别太低。

于 2013-06-11T20:17:51.340 回答
0

要遍历列表,您可以使用

  ListIterator litr = coList.listIterator();
  while(litr.hasNext()){



  }
于 2013-06-13T16:22:19.603 回答
0

尝试使用 foreach 而不是 for

就像

foreach(在 listOfLists 中列出 firstGroup) foreach(在 firstGroup 中的字符串 s)......

于 2013-06-12T17:10:56.467 回答
0

感谢大家的意见和建议!我最终得到了一个列表列表:

导入 java.util.*;

导入搜索.LOBList;公共类数组搜索 {

/**
 * @param args
 */
public static void main(String[] args) {
    LOBList test = new LOBList();
    test.setCompany("80");
    test.setLOB("106");

    LOBList test1 = new LOBList();
    test1.setCompany("80");
    test1.setLOB("601");

    LOBList test2 = new LOBList();
    test2.setCompany("80");
    test2.setLOB("602");

    LOBList test3 = new LOBList();
    test3.setCompany("90");
    test3.setLOB("102");

    LOBList test4 = new LOBList();
    test4.setCompany("90");
    test4.setLOB("102");

    LOBList test5 = new LOBList();
    test5.setCompany("100");
    test5.setLOB("102");

    LOBList BREAK = new LOBList();
    BREAK.setCompany("BREAK");
    BREAK.setLOB("BREAK");
    BREAK.setcompany_lob("BREAK");

     // create arraylist       
      ArrayList<LOBList> arlst=new ArrayList<LOBList>();
      // populate the list
      arlst.add(0,test);
      arlst.add(1,test1);
      arlst.add(2,test2);
      arlst.add(3,test3);
      arlst.add(4,test4);
      arlst.add(5,test5);

         //declare variables
         int idx = 0;
         String nextVal = "";
         //loops through list returned from service, inserts 'BREAK' between different groups of companies
         for(idx=0;idx<arlst.size();idx++){
              String current = arlst.get(idx).getCompany();          
                if(idx != arlst.size()-1){
                    String next = arlst.get(idx+1).getCompany();
                    nextVal = next;
                    if(!(current.equals(next))){
                          arlst.add(idx+1,BREAK);   
                          idx++; 
                      }                                       
                }                   
          }
        //add last break at end of arrayList 
          arlst.add(arlst.size(),BREAK);  
          for(int i=0;i<arlst.size();i++){
              System.out.println("co:" + arlst.get(i).getCompany());
          }
          //master array list
          ArrayList<ArrayList<LOBList>> mymasterList=new ArrayList<ArrayList<LOBList>>();
          mymasterList = searchListCreateNewLists(arlst);
          //print log, prints all elements in all arrays
          for(int i=0;i<mymasterList.size();i++){
              for(int j=0;j<mymasterList.get(i).size();j++){
                  System.out.println("search method: " + mymasterList.get(i).get(j).getCompany());                   
              }
              System.out.println("end of current list");
          }   
}   
//method to loop over company array, finds break, creates new array list for each company group, 
//adds this to a list of lists(masterList) 
public static ArrayList<ArrayList<LOBList>> searchListCreateNewLists(ArrayList<LOBList> list){      
      ArrayList<ArrayList<LOBList>> masterList=new ArrayList<ArrayList<LOBList>>();
      int end = 0;
      int start = 0;
      int index = 0;
      for(int i=0;i<list.size();i++){
          if(list.get(i).getCompany().equals("BREAK")){
              end = i;//end is current index
              masterList.add(new ArrayList<LOBList>());
              for(int j = start;j<end;j++){
                   masterList.get(index).add(list.get(j));
              }
              index++;
              start = i+1;
          }

      }

    return masterList;
}

}

输出为: search method: 80 search method: 80 search method: 80 end of current list search method: 90 search method: 90 end of current list search method: 100 end of current list

因此,所有具有 Company: 80 的公司 LOBList 对象都组合在一个列表中,90 和 100 也是如此。

于 2013-06-13T13:37:29.137 回答