record Sale(String region, String product, int qty, double unitPrice) 목록에서 지역별 총매출(qty * unitPrice 합)을 구하고, 매출이 큰 순서로 정렬해 "region: 12345.0" 형식으로 출력하세요.
데이터: ("KR","pen",10,1.5), ("US","pen",5,2.0), ("KR","book",2,20.0), ("JP","cup",7,3.0), ("US","book",1,25.0).
import java.util.*;
import static java.util.stream.Collectors.*;
public class Ex1 {
record Sale(String region, String product, int qty, double unitPrice) {
double total() { return qty * unitPrice; }
}
public static void main(String[] args) {
List<Sale> sales = List.of(
new Sale("KR", "pen", 10, 1.5), new Sale("US", "pen", 5, 2.0), new Sale("KR", "book", 2, 20.0),
new Sale("JP", "cup", 7, 3.0), new Sale("US", "book", 1, 25.0));
sales.stream()
.collect(groupingBy(Sale::region, summingDouble(Sale::total)))
.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue().reversed())
.forEach(e -> System.out.println(e.getKey() + ": " + e.getValue()));
}
}
// 출력:
// KR: 55.0
// US: 35.0
// JP: 21.0문자열 목록 ["apple", "banana", "avocado", "blueberry", "cherry", "apricot"] 을 첫 글자로 그룹핑하되, 각 그룹은 길이 내림차순으로 정렬된 대문자 리스트여야 합니다. 결과는 키 순으로 정렬된 TreeMap 으로 출력하세요. groupingBy + mapping + collectingAndThen 을 사용하세요.
import java.util.*;
import static java.util.stream.Collectors.*;
public class Ex2 {
public static void main(String[] args) {
List<String> words = List.of("apple", "banana", "avocado", "blueberry", "cherry", "apricot");
Map<Character, List<String>> grouped = words.stream()
.collect(groupingBy(w -> w.charAt(0), TreeMap::new,
mapping(String::toUpperCase,
collectingAndThen(toList(), l -> {
l.sort(Comparator.comparingInt(String::length).reversed());
return l;
}))));
System.out.println(grouped);
}
}
// 출력:
// {a=[AVOCADO, APRICOT, APPLE], b=[BLUEBERRY, BANANA], c=[CHERRY]}1 부터 30 까지의 정수를 IntStream 으로 만들어, 다음을 한 번의 파이프라인 으로 계산하세요: 3 의 배수이거나 5 의 배수인 수들의 개수·합계·평균·최댓값(summaryStatistics). 그리고 같은 조건의 수들을 partitioningBy(짝수) 로 나눠 각각 리스트로 출력하세요.
import java.util.*;
import java.util.stream.*;
import static java.util.stream.Collectors.*;
public class Ex3 {
public static void main(String[] args) {
IntSummaryStatistics st = IntStream.rangeClosed(1, 30)
.filter(n -> n % 3 == 0 || n % 5 == 0)
.summaryStatistics();
System.out.printf("count=%d sum=%d avg=%.2f max=%d%n", st.getCount(), st.getSum(), st.getAverage(), st.getMax());
Map<Boolean, List<Integer>> byEven = IntStream.rangeClosed(1, 30)
.filter(n -> n % 3 == 0 || n % 5 == 0)
.boxed()
.collect(partitioningBy(n -> n % 2 == 0));
System.out.println("even = " + byEven.get(true));
System.out.println("odd = " + byEven.get(false));
}
}
// 출력:
// count=14 sum=225 avg=16.07 max=30
// even = [6, 10, 12, 18, 20, 24, 30]
// odd = [3, 5, 9, 15, 21, 25, 27]