[Stream] 스트림의 종류(Stream, BaseStream)

Stream은 BaseStream이라는 부모 인터페이스가 있고 각각의 자식인터페이스로 다음과 같이 있다.

Stream : 객체요소를 처리하는 스트림

나머지 : 각각의 타입에 맞는 primitive 타입에 대한 요소를 처리

 

컬렉션으로부터 스트림 얻기
public class FromCollectionExample {
	public static void main(String[] args) {
		List<Student> studentList = Arrays.asList(
				new Student("티타늄",10),
				new Student("오리발",5),
				new Student("하하하",30),
				new Student("케케케",24)
		);
		Stream<Student> stream = studentList.stream();
		stream.forEach(s ->System.out.println(s.getName()));
	}
}
/*
티타늄
오리발
하하하
케케케
*/

- 컬렉션 객체에 있는 stream() 메소드를 호출하면 해당 컬렉션 타입에 해당하는 스트림 객체 반환

 

배열로부터 스트림 얻기
public class FromArrayExample {
	public static void main(String[] args) {
		String[] strArray = {"홍길동","강마에","하하하"};
		//배열로부터 스트림 얻음.
		Stream<String> strStream = Arrays.stream(strArray); 
		strStream.forEach(s -> System.out.print(s+",")); //홍길동,강마에,하하하,

		int[] intArray = {1,2,3,4,5};
		IntStream intStream = Arrays.stream(intArray);
		intStream.forEach(s-> System.out.print(s+","));//1,2,3,4,5,	
	}
}

- 배열에서는 Arrays 클래스의 stream() 메소드의 매개값으로 배열을 던지면 해당 타입의 스트림이 반환됨.

 

숫자 범위로부터 스트림 얻기
package Stream.categoryPackage;

import java.util.stream.IntStream;

public class FromIntRangeExample {
	public static int sum;
	public static void main(String[] args) {
		IntStream intStream = IntStream.rangeClosed(1,100);
		intStream.forEach(s-> sum+=s);
		System.out.println("총합 : "+sum); //총합 : 5050
		sum = 0;
		
		intStream = IntStream.range(1,100);
		intStream.forEach(s-> sum+=s);
		System.out.println("총합 : "+sum); //총합 : 4950
	}
}

- rangeClosed() 메소드와 range() 메소드로 매개값의 범위에 해당하는 스트림을 생성

- 두 메소드의 차이는 rangeClosed는 1부터 100까지의 스트림을 얻는 반면, range 메소드는 1부터 99까지의 숫자를 스트림으로 얻는다.

 

파일로부터 스트림 얻기
public class FromFileContentExample {
	public static void main(String[] args) throws IOException{
    	//본인들 파일 아무거나 프로젝트에 만들어서 패키지 주소따라 가시면 됩니다.
		Path path = Paths.get("src/Stream/categoryPackage/linedata.txt");
		Stream<String> stream;
		
		//Files.lines() 메소드 이용, 운영체제의 기본 문자셋
		stream = Files.lines(path, Charset.defaultCharset());
		//메소드참조(s-> System.out.println(s)); 와 동일
		stream.forEach(System.out::println);
		System.out.println();
		
		//BufferedReader의 lines() 메소드 이용
		File file = path.toFile();//패스에 있는 파일을 파일객체로 반환
		FileReader fileReader = new FileReader(file); //파일을 읽음
		BufferedReader br = new BufferedReader(fileReader); //버퍼에다넣음
		//라인별로 스트림에 담음.
		stream = br.lines();
		//라인별로 출력.
		stream.forEach(System.out::println);
	}
}

 

디렉토리로부터 스트림 얻기
public class FromDirectoryExample {
	public static void main(String[] args) throws IOException{
		//본인들 디렉토리 아무거나 파일탐색기에서 긁어오세요.
		Path path = Paths.get("C:/eclipse_practice_workspace");
		Stream<Path> stream = Files.list(path);
		stream.forEach(p->System.out.println(p.getFileName()));
	}
}

- Files 클래스의 list() 메소드에 해당 폴더의 path 정보가있는 Path 클래스를 매개값으로 넣어주면 Path 타입의 스트림을 반환함.

- getFileName() 메소드는 변수 p 아래 존재하는 자식 폴더/파일의 이름을 반환함.

댓글

Designed by JB FACTORY