Collection에서 특정 요소 값 찾기

Stream, Optional을 이용하여, Collection에서 특정 요소를 찾아내는 방법이다.

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

import static org.springframework.test.util.AssertionErrors.assertTrue;

public class StreamTest {

    @Getter
    @Setter
    @ToString
    class Album {
        private String albumName;
        private List<Song> songList;
    }

    @Getter
    @Setter
    @ToString
    class Song {
        private String songName;
    }

    @Test
    public void collectionTest() {

        Album album = new Album();
        album.setAlbumName("앨범명");

        List<Song> songList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Song song = new Song();
            song.setSongName("곡" + i);
            songList.add(song);
        }
        album.setSongList(songList);
        System.out.println(album);  // StreamTest.Album(albumName=앨범명, songList=[StreamTest.Song(songName=곡0), StreamTest.Song(songName=곡1), StreamTest.Song(songName=곡2)])

        String songName = Optional.ofNullable(album)
                .map(Album::getSongList)
                .orElse(Collections.emptyList())
                .stream()
                .filter(song -> song.getSongName().equals("곡2"))
                .map(Song::getSongName)
                .findFirst()
                .orElse("곡명없음");

        assertTrue("에러", "곡2".equals(songName));

        String songName2 = Optional.ofNullable(album)
                .map(Album::getSongList)
                .orElse(Collections.emptyList())
                .stream()
                .filter(song -> song.getSongName().equals("곡4"))
                .map(Song::getSongName)
                .findFirst()
                .orElse("곡명없음");

        assertTrue("에러", "곡명없음".equals(songName2));

    }
}

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 항목은 *(으)로 표시합니다