java8 StringJoiner 과 String.join 활용

2016. 1. 5. 13:39Java


자바 8에서 전부터 숙원했던, SpringJoiner 와 더불어 String.join(...)이 구현 되었다.
Comparator 체인 또는 필드 기반의 비교를 가능하게 하는 새로운 방식을 제안하고 있단다.





Spring Pool의 기본값이 25k ~ 50K 까지 확장 되었다고 한다. 

SpringJoiner is used to construct of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.

Prior to adding something to the StringJoiner , its sj.toString() method will, by default, return prefix + suffix .
However , if the setEmptyValue method is called, the emptyValue supplied will be returned instead.
This can be used, for example, when creating a string using set notation to indicate an empty set,
i.e. "{}", where the prefix is "{", the suffix is "}" and nothing has been added to the StringJoiner.

아래는 예제입니다. 

The String "[George:Sally:Fred]" may be constructed as follows : 

StringJoiner sj = new StringJoiner(":","[","]");
sj.add("George").add("Sally").add("Fred");
String desiredString = sj.toString();

A StringJoiner may be employed to create formatted output from a Stream using Collectors.joining(CharSequence).

List<Integer> numbers = Arrays.asList(1,2,3,4);
String commaSeparatedNumbers = numbers.stream().map(i -> i.toString()).collect(Collectors.joining(", "));


이번에는 String join을 활용해보자.
1) public static String join(CharSequence delimiter , CharSequence ... elements)

String message = String.join("-", "Java" , "is" , "Cool");
//message returned is "Java-is-Cool"

두번째는 
2) public static String join(CharSequence delimiter , Iterator<? extends CharSequence> elements)

List<String> strings = new LinkedList<>();
strings.add("Java");
strings.add("is");
strings.add("Cool");

String message = String.join(" " , strings);
//message returned is "Java is Cool"

Set<String> strings = new LinkedHashSet<>();
strings.add("Java");
strings.add("is");
strings.add("very");
strings.add("cool");
String message = String.join("-",strings);
//message return is : "Java-is-very-cool"



그렇다.



'Java' 카테고리의 다른 글

core java 따라하기 - 2  (0) 2017.06.15
core java 따라하기 - 1  (0) 2017.06.13
JUnit5 개념 잡기  (0) 2017.06.02
ThreadLocal 이 뭘까요?  (0) 2016.01.05
Apache Daemon 에 대해서  (3) 2015.12.08
Runtime.addShutdownHook()  (0) 2015.09.30
Top 10 Useful, Yet paranoid Java Programming Techniques  (0) 2015.09.15
Exception  (0) 2013.08.04
Regular Expressions in Java  (0) 2013.07.30
Delegate, Event , Ramda  (0) 2013.07.04