Java/16. 스트림과 병렬 처리
Day 22 : 연습 문제
pancakemaker
2021. 11. 17. 17:55
1. 스트림에서 합계와 카운트 구하기
package sec02.stream_kind;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class FromArrayExample {
public static void main(String[] args) {
String[] strArray = { "홍길동", "신용권", "김미나" };
//배열로부터 스트림 얻기
Stream<String> strStream = Arrays.stream(strArray);
strStream.forEach( a -> System.out.print(a + ","));
System.out.println();
//배열로부터 스트림 얻기
int[] intArray = { 1, 2, 3, 4, 5 };
IntStream intStream = Arrays.stream(intArray);
intStream.forEach( a -> System.out.print(a + ","));
System.out.println();
int sumVal = Arrays.stream(intArray).sum();
int count = (int) Arrays.stream(intArray).count();
System.out.println(sumVal);
System.out.println(count);
}
}
홍길동,신용권,김미나,
1,2,3,4,5,
15
5
2. 이름 정렬하기
package sec06.stream_sorting;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class ArrayListStreamTest {
public static void main(String[] args) {
List<String> sList = new ArrayList<String>();
sList.add("Thomas");
sList.add("Edward");
sList.add("Jack");
Stream<String> stream = sList.stream(); //스트림 생성
stream.forEach( s -> System.out.print(s + " ") );
System.out.println();
//이름 정렬하기 (오름차순)
sList.stream().sorted().forEach( s -> System.out.print(s + " ") );
}
}
Thomas Edward Jack
Edward Jack Thomas
3. 길이가 가장 긴 문자열 추출
package sec10.stream_reduce;
import java.util.Arrays;
import java.util.function.BinaryOperator;
class CompareString implements BinaryOperator<String> {
@Override
public String apply(String s1, String s2) {
if(s1.getBytes().length >= s2.getBytes().length) {
return s1;
} else {
return s2;
}
}
}
public class ReduceTest {
public static void main(String[] args) {
String[] greetings = {"안녕하세요", "Hello", "Good Morning", "반갑습니다"};
System.out.println(
Arrays.stream(greetings).reduce("", (a, b) -> {
if(a.getBytes().length >= b.getBytes().length) return a;
else return b;
}));
System.out.println();
String str = Arrays.stream(greetings).reduce(new CompareString()).get();
System.out.println(str);
}
}
Good Morning
Good Morning
4. 여행객 정보
package sec06.stream_sorting;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
//1. 고객의 명단을 출력합니다.
//2. 여행의 총 비용을 계산합니다.
//3. 고객 중에서 나이가 20 이상인 사람의 이름을 정렬하여 출력합니다.
public class TravelTest {
public static void main(String[] args) {
TravelCustomer customerLee = new TravelCustomer("이순신", 40, 100);
TravelCustomer customerKim = new TravelCustomer("김유신", 20, 100);
TravelCustomer customerHong = new TravelCustomer("홍길동", 13, 50);
List<TravelCustomer> customerList = new ArrayList<>();
customerList.add(customerLee);
customerList.add(customerKim);
customerList.add(customerHong);
System.out.println("1. 고객의 명단을 출력합니다.");
customerList.stream().map( n -> n.getName() ).forEach( n -> System.out.print(n + " ") );
/*
stream.forEach( n -> {
String name = n.getName();
System.out.print(name + " ");
});
*/
System.out.println();
int total = 0;
total = customerList.stream().mapToInt(TravelCustomer :: getPrice).sum();
System.out.println("2. 총 여행 비용은: " + total + " 입니다.");
System.out.println("3. 고객 중에서 나이가 20세 이상인 고객은");
//customerList.stream().filter(c -> c.getAge() >= 20).map( c -> c.getName() ).sorted().forEach( s -> System.out.print(s + " ") );
customerList.stream().filter( a -> a.getAge() >= 20).sorted().forEach( a -> System.out.print(a.getName() + " ") );
//중간에 map을 넣으면 TravelCustomer 클래스가 Comparable 구현하지 않아도 됨 (map에서 name을 호출 즉, String 타입이므로 자동으로 구현되어 있음
//filter()뒤에 sorted() 넣으면 클래스가 Comparable 구현하지 않으면 Exception 발생 -> 사용자 정의 클래스가 Comparable을 구현해야 함!
System.out.println("입니다.");
}
}
1. 고객의 명단을 출력합니다.
이순신 김유신 홍길동
2. 총 여행 비용은: 250 입니다.
3. 고객 중에서 나이가 20세 이상인 고객은
김유신 이순신 입니다.
5. 서점의 책 정보
package sec06.stream_sorting;
import java.util.ArrayList;
import java.util.List;
class Book {
String name; //책 제목
int price; //책 가격
Book(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
public class LibraryTest {
public static void main(String[] args) {
List<Book> bookList = new ArrayList<Book>();
bookList.add(new Book("자바", 25000));
bookList.add(new Book("파이썬", 15000));
bookList.add(new Book("안드로이드", 35000));
//1. 모든책의 가격의 합
int totalPrice = bookList.stream().mapToInt( Book :: getPrice ).sum();
System.out.println("모든 책의 가격의 합은 " + totalPrice + "원 입니다.");
//2. 책의 가격이 20000원 이상인 책의 이름을 정렬하여 출력
System.out.println("가격이 20000원 이상인 책의 이름은 ");
bookList.stream().filter( p -> p.getPrice() >= 20000 ).map( Book :: getName ).sorted().forEach( n -> System.out.print(n + " ") );
//중간에 map을 넣으면 Book 클래스가 Comparable 구현하지 않아도 됨 (map에서 name을 호출 즉, String 타입이므로 자동으로 구현되어 있음
//filter()뒤에 sorted() 넣으면 클래스가 Comparable 구현하지 않으면 Exception 발생 -> 사용자 정의 클래스가 Comparable을 구현해야 함!
System.out.print("입니다.");
}
}
모든 책의 가격의 합은 75000원 입니다.
가격이 20000원 이상인 책의 이름은
안드로이드 자바 입니다.