簡體   English   中英

如何在java中操作列表

[英]how to manipulate list in java

編輯: 我的列表是按來自數據庫的順序排序我有一個具有類People對象的ArrayList。 人們有兩個屬性:ssn和terminationReason。 所以我的列表看起來像這樣

ArrayList: 
ssn            TerminatinoReason
123456789      Reason1
123456789      Reason2
123456789      Reason3
568956899      Reason2
000000001      Reason3
000000001      Reason2

我想更改此列表,以便沒有重復項,並且終止原因由逗號分隔。

所以上面的列表將成為

New ArrayList: 
ssn            TerminatinoReason
123456789      Reason1, Reason2, Reason3
568956899      Reason2
000000001      Reason3, Reason2

我有一些東西在我循環原始列表並匹配ssn,但它似乎不起作用。

有人可以幫忙嗎?

我使用的代碼是:

    String ssn = "";
    Iterator it = results.iterator();
    ArrayList newList = new ArrayList();
    People ob;
    while (it.hasNext())
    {
       ob = (People) it.next();
       if (ssn.equalsIgnoreCase(""))
       {
           newList.add(ob);
           ssn = ob.getSSN();
       }
       else if (ssn.equalsIgnoreCase(ob.getSSN()))
       {
           //should I get last object from new list and append this termination reason?
            ob.getTerminationReason()
       }
    }

對我來說,這似乎是一個使用Multimap的好例子,它允許為單個鍵存儲多個值。

Google Collections有一個Multimap實現。

這可能意味着Person對象的ssnterminationReason字段可能必須分別取出為鍵和值。 (這些字段將被假定為String 。)

基本上,它可以使用如下:

Multimap<String, String> m = HashMultimap.create();

// In reality, the following would probably be iterating over the
// Person objects returned from the database, and calling the
// getSSN and getTerminationReasons methods.

m.put("0000001", "Reason1");
m.put("0000001", "Reason2");
m.put("0000001", "Reason3");
m.put("0000002", "Reason1");
m.put("0000002", "Reason2");
m.put("0000002", "Reason3");

for (String ssn : m.keySet())
{
    // For each SSN, the termination reasons can be retrieved.
    Collection<String> termReasonsList = m.get(ssn);

    // Do something with the list of reasons.
}

如有必要,可以生成以逗號分隔的Collection列表:

StringBuilder sb = new StringBuilder();

for (String reason : termReasonsList)
{
    sb.append(reason);
    sb.append(", ");
}

sb.delete(sb.length() - 2, sb.length());
String commaSepList = sb.toString();

這可以再次設置為terminationReason字段。

正如Jonik在評論中提到的,另一種方法是使用Apache Commons中StringUtils.join方法Lang可以用來創建逗號分隔列表。

還應注意, Multimap沒有指定實現是否應該允許重復的鍵/值對,因此應該查看要使用的Multimap類型。

在此示例中, HashMultimap是一個不錯的選擇,因為它不允許重復的鍵/值對。 這將自動消除為某個特定人員提供的任何重復原因。

List<People> newlst = new ArrayList<People>();
People last = null;
for (People p : listFromDB) {
   if (last == null || !last.ssn.equals(p.ssn)) {
      last = new People();
      last.ssn = p.ssn;
      last.terminationReason = "";
      newlst.add(last);  
   }
   if (last.terminationReason.length() > 0) {
      last.terminationReason += ", ";
   }
   last.terminationReason += p.terminationReason;
}

並且您獲得了newlst中的聚合列表。

更新:如果您使用的是MySQL,則可以使用GROUP_CONCAT函數以所需格式提取數據。 我不知道其他數據庫引擎是否具有類似的功能。

更新2:刪除了不必要的排序。

您可能需要的是哈希。 HashMap可能有用。

覆蓋People類中的equals()和hashCode()。

使hashCode返回人(人)SSN。 這樣,您將在同一個“存儲桶”中擁有具有相同SSN的所有People對象。

請記住,Map接口實現類使用鍵/值對來保存對象,因此您將擁有類似myHashMap.add(“ssn”,peopleobject)的內容;

兩個可能的問題:

  • 如果您的列表未排序,則無效
  • 你沒有用ob.getTerminationReason()做任何事情。 我認為你的意思是將它添加到上一個對象。

編輯:現在我看到你編輯了你的問題。

當您的列表被排序時,(由ssn我推測)

Integer currentSSN = null;
List<People> peoplelist = getSortedList();//gets sorted list from DB.
/*Uses foreach construct instead of iterators*/

for (People person:peopleList){

 if (currentSSN != null && people.getSSN().equals(currentSSN)){
 //same person
 system.out.print(person.getReason()+" ");//writes termination reason

 } 
 else{//person has changed. New row.
   currentSSN = person.getSSN();
   system.out.println(" ");//new row.
   system.out.print(person.getSSN()+ " ");//writes row header.
 }

}

如果您不想顯示列表的內容,可以使用它來創建MAP,然后使用它,如下所示。

如果您的列表未排序

也許你應該嘗試一種不同的方法,使用Map。 在這里,ssn將是地圖的關鍵,值可以是人員列表

Map<Integer,List<People>> mymap = getMap();//loads a Map from input data.

for(Integer ssn:mymap.keyset()){
 dorow(ssn,mymap.get(ssn));
}

public void dorow(Integer ssn, List<People> reasons){

system.out.print(ssn+" ");
for (People people:reasons){
system.out.print(people.getTerminationReason()+" ");
}

system.out.println("-----");//row separator.

最后但並非最不重要的,您應該覆蓋People類上的hashCode()和equals()方法。

例如

public void int hashcode(){

  return 3*this.reason.hascode();

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM