Java

[JAVA] 리소스로부터 스트림 얻기

개바리여리 2025. 10. 13. 21:45

BaseStreaam 인터페이스를 통하여 자식 인터페이스들은 다음과 같은 상속관계를 가지며 

기본타입의 스트림과 객체타입의 스트림을 사용할 수 있다.

 

 

배열로부터 스트림을 얻는 방법

 

Arryas 클래스를 이용하여 다양한 종류의 배열로부터 스트림을 얻을 수 있다.

 

public class Main {
    public static void main(String[] args) {
        String[] strArray = { "홍길동", "아무개", "손흥민" };
        Stream<String> stringStream = Arrays.stream(strArray);
        stringStream.forEach(item -> System.out.println(item + ","));

        System.out.println();
        
        int[] intArrays = { 1, 2, 3, 4, 5 };
        IntStream intStream = Arrays.stream(intArrays);
        intStream.forEach(item -> System.out.println(item + ","));
    }
}

 

참고로 스트림은 기본적으로 인덱스를 제공하지 않지만 꼼수를 부려서 인덱스 기반으로 보이게 할 수 있다.

String[] names = { "홍길동", "아무개", "손흥민", "이강인", "박지성" };
IntStream.range(0, names.length)
	.filter(i -> i != 1 && i != 3) // 인덱스 1,3 건너뛰기
    .mapToObj(i -> names[i])
    .forEach(System.out::println);

 

range는 마지막숫자를 포함하지 않고, rangClosed는 마지막 숫자를 포함하여 연산을 한다.

 

public static void main(String[] args){
	IntStream stream = IntStream.rangeClosed(1, 100);
    stream.forEach(a ->  sum += a);
    System.out.println("총합 : " + sum);
}  //총합 5050

 

 

중간처리 (요소 걸러내기, 필터링)

distinct(), filter() 가 존재한다.

 

public class FilteringExample{

	public static void main(String[] args){
    	
        List<String> list = new ArrayList<>();
        list.add("남궁승현"); 
        list.add("한구"); 
        list.add("김승현"); 
        list.add("김승현");
        list.add("최현");
        
        //중복값 제거
        list.stream()
        .distinct()
        .forEach(n -> System.out.println(n));
        
        //결과: 남궁승현, 한구, 김승현, 최현 
        
        //이름이 3글자 이상만
        list.stream()
        .filter(n -> n.length >= 3)
        .forEach(n -> System.out.println(n));
        //결과: 남궁승현, 김승현, 김승현
        
    }
}

 

 

요소 변환 (매핑)

스트림의 요소를 다른 요소로 변환하는 중간 처리 기능.

class Student {
    private String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }
    public int getScore() {
        return score;
    }
}

public class Main {
    public static void main(String[] args) {

        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("홍길동", 85));
        studentList.add(new Student("홍길동", 92));
        studentList.add(new Student("홍길동", 87));

        IntStream intStr = studentList.stream()
                .mapToInt(s -> s.getScore());

        //////

        int[] intArray = { 1,2,3,4,5};

        IntStream intStream = Arrays.stream(intArray);
        intStream.boxed().forEach(obj -> System.out.println(obj)); //Integer로 박싱

    }
}

 

요소를 복수 개의 요소로 변환

flatMap 메서드는 하나의 요소를 복수개의 요소들로 변환한 새로운 스트림을 리턴한다.

 List<String> list1 = new ArrayList<>();
        list1.add("this is java");
        list1.add("i am developer");
        list1.stream()
                .flatMap(data -> Arrays.stream(data.split(" ")))
                .forEach(System.out::println);

 

 

요소를 하나씩 처리 (루핑)

스트림에서 요소를 하나씩 반복해서 가져와 처리하는 것을 말한다. peek 와 forEach가 있다.

peek는 중간처리 메소드이고 forEach는 최종처리  메소드이다.

 

int[] intArr = {1,2,3,4,5};

       Arrays.stream(intArr).filter(a -> a%2==0)
               .peek(System.out::println);

       int total = Arrays.stream(intArr)
               .filter(a -> a%2 == 0)
               .peek(n -> System.out.println(n))
               .sum(); //최종처리

       Arrays.stream(intArr)
               .filter(a -> a%2 == 0)
               .forEach(n -> System.out.println(n)); //최종처리