Map의 요소로 문자열 만들기

taehoon·2023년 11월 8일
0

( JAVA ) Stream

목록 보기
4/5
String result = data.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .map(entry -> {
                    Quote quote = entry.getValue();
                    return String.format("%d / %s / %s / %s", entry.getKey(),
                            quote.getAuthor(), quote.getContent(), quote.getLocalDateTime());
                })
                .collect(Collectors.joining("\n", "번호 / 작가 / 명언\n----------------------\n", ""));

Map.entrySet()

  • KeySet()과 비슷하지만 key와 value를 함께 갖는 요소인 entry를 Set으로 가져온다.

  • Map과 entrySet은 Map의 요소를 순차적으로 접근할 수 있다는 차이가 있다.

.collect(Collectors.joining(delimiter, prefix, suffix))

> delimiter : 요소 사이사이에 들어갈 문자열
  여기서는 줄바꿈을 위해서 "\n"을 주었다.
> prefix : 결과 문자열의 가장 앞에 삽입될 문자열
> suffix : 결과 문자열의 가장 뒤에 삽입될 문자열
  • collect()는 Collector 인터페이스를 구현한 객체 인수로 받는다. Collectors.joining()을 하게 되면 요소들을 하나의 String으로 연결하는 객체를 생성한다.
    즉, collect()는 Collector객체의 기능을 실행하기 위한 껍데기이다.
profile
건강

0개의 댓글