Below code converts a list of type List<TestObj> to a list of type List<List<String>> where each List element in type List<List<String>> is a string list of size 1. This is a very iterative approach, whether it can be converted to more functional method using scala? Possible solution: match patterns on List<String> and just create a new list with each title element?
The output of the bottom Java code:
strVal is 1 New list strVal is 2 New list public class Driver { public static void main (String args[]){ 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); 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; } } } } 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; } }
source share