」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何有效地在Java中串聯串聯列表?

如何有效地在Java中串聯串聯列表?

發佈於2025-03-22
瀏覽:606

How Can I Efficiently Concatenate Lists of Strings in Java?
java:有效地將字符串列表

在Java中,有幾種方法可以將多個字符串從列表中組合到單個字符串中。雖然可以手動創建一個循環並將每個字符串附加到一個字符串構造器上,並檢查第一個字符串並相應地添加一個分離器,但此方法可能很麻煩。

public static String join(CharSequence delimiter, Iterable extends CharSequence> elements)

Where:

delimiter: The separator to place between each element in the output stringelements: An iterable collection of CharSequences (i.e., Strings) to可以加入

示例,with string.join()

使用string.join():
public static String join(CharSequence delimiter, Iterable extends CharSequence> elements)

Collectors.joining() for Non-String Elements
  • For collections of non-String elements, you can leverage the Collectors.joining() method in conjunction with the stream API:
  • List people = Arrays.asList( 新人(“約翰”,“史密斯”), 新人(“ Anna”,“ Martinez”), 新人(“保羅”,“沃森”) ); 字符串加入FirstNames = People.Stream() .map(person :: getfirstname) .Collect(collectors.joining(“,”)); //“ John,Anna,paul”
stringjoiner用於更多控制

公共類String Joiner { String Joiner(CharSequence定界符) } ”); joiner.add(“蘋果”); joiner.add(“橙色”); joiner.add(“香蕉”); 字符串結果= joiner.tostring(); //“ [蘋果,橙色,香蕉]”

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3