반응형

환경: java11

 

요구사항: size 5인 array에 데이터를 넣고 없으면 빈 값으로 입력

String motionAvatar = "1022,1,,,"
int motionAvatarCount = 5;
String[] motionAvatarDetails = Stream
                                .concat(this.motionAvatar.split(","), Stream.generate(() -> ""))
                                .limit(motionAvatarCount)
                                .toArray(String[]::new);
                                
    //["1022", "1", "", "", ""]
  1. Stream.generate(() -> "") creates an infinite stream of empty strings.
  2. Stream.concat(...) concatenates the split array with the stream of empty strings.
  3. limit(motionAvatarCount) limits the concatenated stream to motionAvatarCount elements.
  4. toArray(String[]::new) converts the limited stream into an array of strings.

for loop 안돌고 세련된 방법으로 해보고 싶었는데 stream.generate 는 처음 봤다..

728x90
반응형

+ Recent posts