# Language/Java

[Java 8] Stream 정렬 예제 메모

import lombok.Getter;
import lombok.ToString;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * MyMockTest class.
 * <PRE>
 * Describe here.
 * </PRE>
 *
 * <PRE>
 * <B>History:</B>
 * damian.lee, 0.0.1, Created at 2022.08.22
 * </PRE>
 *
 * @author : damian
 * @version : 0.0.1
 */
public class MyMockTest extends BaseMockTest {

    @Test
    @DisplayName("")
    void test_MyTest() throws Exception {
        // given
        List<MyItem> items = new ArrayList<>();
        items.add(new MyItem(1L, null));
        items.add(new MyItem(7L, null));
        items.add(new MyItem(2L, 1L));
        items.add(new MyItem(6L, 4L));
        items.add(new MyItem(3L, null));
        items.add(new MyItem(5L, 4L));
        items.add(new MyItem(4L, null));

        // when
        List<MyItem> parents = items.stream()
                .filter(i -> i.parentId == null)
                .sorted(Comparator.comparing(MyItem::getId).reversed())
                .collect(Collectors.toList());

        List<MyItem> childs = items.stream()
                .filter(i -> i.parentId != null)
                .collect(Collectors.toList());

        // then
        List<MyItem> result = new ArrayList<>();
        for (MyItem i : parents) {

            // Insert Parent
            result.add(i);

            // Get Child
            result.addAll(
                    childs.stream()
                            .filter(item -> item.getParentId().equals(i.getId()))
                            .sorted(Comparator.comparing(MyItem::getId).reversed())
                            .collect(Collectors.toList())
            );
        }

        System.out.println("##### Result");
        for (MyItem i : result) {
            System.out.println(i);
        }

    }

    @Getter
    @ToString
    private class MyItem {
        private Long id;
        private Long parentId;

        public MyItem(Long id, Long parentId) {
            this.id = id;
            this.parentId = parentId;
        }

    }

}

 

Before

(id, parentId)

1, null

7, null

2, 1

6, 4

3, null

5, 4

4, null

 

 

After

MyMockTest.MyItem(id=7, parentId=null)
MyMockTest.MyItem(id=4, parentId=null)
MyMockTest.MyItem(id=6, parentId=4)
MyMockTest.MyItem(id=5, parentId=4)
MyMockTest.MyItem(id=3, parentId=null)
MyMockTest.MyItem(id=1, parentId=null)
MyMockTest.MyItem(id=2, parentId=1)

728x90