2013-02-07 103 views
4

下面的代碼List<TestObj>類型的列表轉換爲類型List<List<String>> 的列表,其中在List<List<String>>類型每個列表元素是 大小爲1的字符串列表這是一個非常迭代方法,可以使用scala將其轉換爲更實用的 方法嗎? 一個可能的解決方案:模式匹配List<String>,並創建一個新的列表與 每個頭元素?如何轉換用java斯卡拉集合轉換

輸出的下面Java代碼:

strVal is 1 
New list 
strVal is 2 
New list 


public class Driver { 

     public static void main (String args[]){ 

     /** 
     * Setup the test list data 
     */ 
     List<String> l = new ArrayList<String>(); 
     l.add("1"); 
     l.add("2");  
     TestObj t = new TestObj(); 
     t.setTestList(l); 
     t.setName("test"); 
     List<TestObj> tList = new ArrayList<TestObj>(); 
     tList.add(t); 

     /** 
     * Convert the list to a new data structure 
     */ 
     List<List<String>> l3 = new ArrayList<List<String>>(); 
     List<String> l2 = new ArrayList<String>();  
     int counter = 0; 
     for(TestObj tListElement : tList){ 
      if(tListElement.getName().equalsIgnoreCase("test")){ 
      List<String> lvo = tListElement.getTestList();  
      for(String lv : lvo){ 
       l2.add(lv); 
       ++counter; 
       if(counter == 1){ 
        counter = 1; 
        l3.add(l2); 
        l2 = new ArrayList<String>(); 
        counter = 0; 
       } 
      } 
     } 
     } 

     /** 
     * Output the values of the new data structure 
     */ 
     for(List<String> listVals : l3){ 
      for(String strVal : listVals){ 
       System.out.println("strVal is "+strVal); 
      } 
      System.out.println("New list"); 
     } 
    } 
} 

import java.util.List; 


public class TestObj { 

    private String name; 
    private List<String> testList; 

    public String getName() { 
     return name; 
    } 
    public void setName(String name) { 
     this.name = name; 
    } 
    public List<String> getTestList() { 
     return testList; 
    } 
    public void setTestList(List<String> testList) { 
     this.testList = testList; 
    } 

} 

回答

5
case class TestObj(name: String, testList: Seq[String]) 

object Driver extends App { 

    // Setup the test list data 
    val tList = Seq(TestObj("test", Seq("1", "2"))) 

    // Convert the list to a new data structure 
    val l3 = for { 
     t <- tList 
     if t.name equalsIgnoreCase "test" 
     lv <- t.testList 
    } yield Seq(lv) 

    // Output the values of the new data structure 
    for (listVals <- l3) { 
    for (strVal <- listVals) { 
     println("strval is " + strVal) 
    } 
    println("New list") 
    } 

} 
+4

獎勵用於讀取和翻譯的Java代碼。我已經使用了14年的Java和3年的Scala。對於我來說,搞清楚Scala代碼的功能要快得多。我甚至不知道Java代碼的作用...... – huynhjl

+2

@ Ptharien的火焰如果可以的話,我會贊成幾次,謝謝。 –