스트림

(。◠ ◠。)·2022년 7월 29일

국비 개발 훈련 일기

목록 보기
10/35

// 스트림
// 여러자료에대한 처리를 미리 구현해 놓은 클래스.
// 스트림을 활용하면 배열 컬렉션 등의 자료를 일관성 있게 처리할 수 있게 해준다.

		int[] arr= {1,2,3,4,5};
		for(int i = 0; i<arr.length;i++){
			System.out.print(arr[i]+" ");
		}

이렇게 줄일 수 있다.

		Arrays.stream(arr).forEach(n->System.out.print(n+" "));

// 중간연산 최종연산
// 중간연산
// 1. filter() : 조건이 참일 경우만 추출한다.
sList.stream().filter(s->s.lenth()>=5).forEach(s->System.out.println(s));

// 2. map() : 클레스가 가진 자료 중 이름만 출력하는 경우에 사용
customerList.stream().map(c->c.getName()).forEach(s->System.out.println(s));

// 스트림은 소모된다. 최종연산 시 스트림은 모두 소멸된다.
// 1)자료의 대상과 관계없이 동일한 연산을 수행한다
// 2)한 번 생성하고 사용한 스트림은 재사용할 수 없다
// 3)스트림의 연산은 기존 자료를 변경하지 않는다
// 4)스트림의 연산은 중간연산과 최종연산이 있다

// 최종연산
// 1) forEach() : 요소를 하나씩 꺼내는 기능.
// 2) sum() : 요소들의 합을 구하는 기능.
// 3) count() : 요소들의 개수를 구하는 기능.
// 4) reduce() : reduce(초기값, 연산) 형식으로 사용합니다. 초기값부터 시작하여 각 원소를 차례대로 순회하며 연산을 수행합니다.

//	2) sum() : 요소들의 합을 구하는 기능.
	int sumVal = Arrays.stream(arr).sum();
	System.out.println("합계 "+sumVal);
	
//	3) count() : 요소들의 개수를 구하는 기능.
	long count = Arrays.stream(arr).count();
	System.out.println("개수 "+count);
    
//	1) forEach() : 요소를 하나씩 꺼내는 기능.
	List<String>sList=new ArrayList<>();
	sList.add("다");
	sList.add("나");
	sList.add("가");
	
	Stream<String>stream=sList.stream();
	stream.forEach(s->System.out.print(s+" "));
	
    하나씩 꺼내는데 오름차순으로 정렬해서 꺼내줌
	sList.stream().sorted().forEach(s->System.out.print(s+" "));

.
문자열 순서가 긴거 구하기..

	@Override
	public String apply(String t, String u) {
		
		if(t.getBytes().length>=u.getBytes().length) return t;
		else return u;
	}
}

public class ReduceTest {
	public static void main(String[] args) {
		String[] greeting= {"안녕하세요","hello","Good moring","반가워요반갑나요진짜요"};
		System.out.println(
				Arrays.stream(greeting).reduce("", (s1,s2)->{
					if(s1.getBytes().length>=s2.getBytes().length)
						return s1;
					else return s2;
				})
		);
		
		String str = Arrays.stream(greeting).reduce(new CompareString()).get();
		System.out.println(str);		
	}
}
		TravelCustomer custLee = new TravelCustomer("이순신", 40, 100);
		TravelCustomer custKim = new TravelCustomer("김유신", 20, 100);
		TravelCustomer custHong = new TravelCustomer("홍길동", 13, 50);
		
		
		List<TravelCustomer> custList = new ArrayList<>();
		custList.add(custLee);
		custList.add(custKim);
		custList.add(custHong);
        
        
		System.out.println("고객명단출력");
		custList.stream().map(c->c.getName()).forEach(s->System.out.println(s));
		
        System.out.println("여행경비출력");
		int total = custList.stream().mapToInt(c->c.getPrice()).sum();
		System.out.println(total);
		
		System.out.println("20세이상고객명단정렬");
		custList.stream().filter(c-> c.getAge()>= 20)
		.map(c->c.getName()).sorted().forEach(s->System.out.println(s));
profile
화이탱!

0개의 댓글