場景介紹
要將list 集合中的某一個字段合並成一個字符串,並且要用符號 “|” 分割開每個拼接后的字段。
一個例子勝於一切的文字表達,拼接后的結果如下
str1|str2|str3|strn
其實用for 循環很簡單就可以實現了,但可能你更喜歡遞歸的方式實現。
代碼實現:
public static void main(String[] args) { Stu stu1 = new Stu("張三",18); Stu stu2 = new Stu("李四",18); Stu stu3 = new Stu("王五",18); List<Stu> list = new ArrayList<Stu>(); list.add(stu1); list.add(stu2); list.add(stu3); String loopJoint = loopJointDESC(list, list.size()); System.out.println(loopJoint); } /** * 實現學生集合的姓名拼接:name1|name2|nameN * @param list * @param size 控制遞歸次數(size=list.size()) * @return */ public static String loopJointDESC(List<Stu> list,int size ) { if(list.size()<=0) return null; if(size==1) return list.get(0).getName(); String joinStr = "|"; size--;//下標值和遞歸次數減少1 String name = list.get(size).getName(); String loopJoint = loopJointDESC(list, size); return name+joinStr+loopJoint; }
實體類
public class Stu { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Stu(String name, Integer age) { super(); this.name = name; this.age = age; } public Stu() { super(); } }
測試結果
發現反過來拼接了,於是改為
public static String loopJointASC(List<Stu> list,int size ) { if(list.size()<=0) return null; if(size==1) return list.get(list.size()-1).getName(); String joinStr = "|"; String name = list.get(list.size()-size).getName(); size--;//下標值和遞歸次數減少1 String loopJoint = loopJointASC(list, size); return name+joinStr+loopJoint; }
測試結果
分隔符 “|” 可自己定義也可以刪除。
最后留下兩個問題:
當list非常大的時候,使用for 循環和遞歸哪種實現方式的速度更快呢?
雙層for 循環改為,for循環+遞歸性能會不會更好呢?
更多優質文章、學習資源、IDEA激活碼等請關注👇