Java8 의 Stream 에 대해 알고는 있지만 제대로 써 본적이 없었는데 망나니 개발자님 블로그를 보다가 Stream API 연습문제 풀이 글이 있어서 문제들을 풀어보았다.
1번 문제 모음
[데이터]
이름, 취미, 소개
김프로, 축구:농구:야구, 구기종목 좋아요
정프로, 개발:당구:축구, 개발하는데 뛰긴 싫어
앙몬드, 피아노, 죠르디가 좋아요 좋아좋아너무좋아
죠르디, 스포츠댄스:개발, 개발하는 죠르디 좋아
박프로, 골프:야구, 운동이 좋아요
정프로, 개발:축구:농구, 개발도 좋고 운동도 좋아
[문제 1]
위와 같은 데이터를 조회하여 각 취미를 선호하는 인원이 몇 명인지 계산하여라.
users.stream()
.flatMap(user -> user.getHobbies().stream())
.collect(Collectors.groupingBy(hobby -> hobby, Collectors.counting()))
.forEach((hobby, count) -> System.out.println(hobby + " : " + count));
[문제 2]
위와 같은 데이터를 조회하여 각 취미를 선호하는 정씨 성을 갖는 인원이 몇 명인지 계산하여라.
users.stream()
.filter(user -> user.getName().startsWith("정"))
.flatMap(user -> user.getHobbies().stream())
.collect(Collectors.groupingBy(hobby -> hobby, Collectors.counting()))
.forEach((hobby, count) -> System.out.println(hobby + " : " + count));
[문제 3]
위와 같은 데이터를 조회하여 소개 내용에 '좋아'가 몇번 등장하는지 계산하여라.
users.stream()
.map(User::getIntroduction)
.map(this::getLikeCount)
.reduce(Integer::sum)
.ifPresent(System.out::println);
2번 문제 모음
[데이터]
private final static List<String> WORDS = Arrays.asList("TONY", "a", "hULK", "B", "america", "X", "nebula", "Korea");
[문제 1]
List에 저장된 단어들의 접두사가 각각 몇개씩 있는지 Map<String, Integer>으로 변환하여라. ex) ("T", 1), ("a", 2) ...
WORDS.stream()
.map(word -> word.substring(0, 1))
.collect(Collectors.groupingBy(word -> word, Collectors.counting()))
.forEach((prefix, count) -> System.out.println(prefix + " : " + count));
[문제 2]
List에 저장된 단어들 중에서 단어의 길이가 2 이상인 경우에만, 모든 단어를 대문자로 변환하여 스페이스로 구분한 하나의 문자열로 합한 결과를 반환하여라. ex) ["Hello", "a", "Island", "b"] -> “H I”
String result = WORDS.stream()
.filter(word -> word.length() >= 2)
.map(String::toUpperCase)
.map(word -> word.substring(0, 1))
.collect(Collectors.joining(" "));
System.out.println(result);
3번 문제 모음
[데이터]
private static final List<Integer> numbers1 = Arrays.asList(1, 2, 3);
private static final List<Integer> numbers2 = Arrays.asList(3, 4);
[문제 1]
위와 같은 숫자 리스트가 있을 때 모든 숫자 쌍의 배열 리스트를 반환하여라.
ex) numbers1 = [1,2,3], numbers2 = [3,4] -> [(1,3), (1,4), (2,3), (2,4), (3,3), (3,4)]
List<Pair<Integer, Integer>> result = numbers1.stream()
.map(number1 -> numbers2.stream().map(number2 -> Pair.of(number1, number2)).collect(Collectors.toList()))
.flatMap(List::stream)
.toList();
System.out.println(result);
[문제 2]
위와 같은 숫자 리스트가 있을 때 모든 숫자 쌍의 곱이 가장 큰 값을 반환하여라.
ex) numbers1 = [1,2,3], numbers2 = [3,4] -> 12
numbers1.stream()
.map(number1 -> numbers2.stream().map(number2 -> Pair.of(number1, number2)).collect(Collectors.toList()))
.flatMap(List::stream)
.reduce((pair1, pair2) -> pair1.getLeft() * pair1.getRight() > pair2.getLeft() * pair2.getRight() ? pair1 : pair2)
.ifPresent(pair -> System.out.println(pair.getLeft() * pair.getRight()));
4번 문제 모음
[데이터]
public class Trader {
private String name;
private String city;
}
public class Transaction {
private Trader trader;
private int year;
private int value;
}
public void init() {
Trader kyu = new Trader("Kyu", "Seoul");
Trader ming = new Trader("Ming", "Gyeonggi");
Trader hyuk = new Trader("Hyuk", "Incheon");
Trader hwan = new Trader("Hwan", "Seoul");
transactions = Arrays.asList(
new Transaction(kyu, 2019, 30000),
new Transaction(kyu, 2020, 12000),
new Transaction(ming, 2020, 40000),
new Transaction(ming, 2020, 7100),
new Transaction(hyuk, 2019, 5900),
new Transaction(hyuk, 2020, 4900)
);
}
[문제 1]
2020년에 일어난 모든 거래 내역을 찾아 거래값을 기준으로 오름차순 정렬하라.
transactions.stream()
.filter(transaction -> transaction.getYear() == 2020)
.sorted(Comparator.comparingInt(Transaction::getValue))
.forEach(System.out::println);
[문제 2]
거래 내역이 있는 거래자가 근무하는 모든 도시를 중복 없이 나열하라.
transactions.stream()
.map(Transaction::getTrader)
.map(Trader::getCity)
.distinct()
.forEach(System.out::println);
[문제 3]
서울에서 근무하는 모든 거래자를 찾아서 이름순서대로 정렬하라.
transactions.stream()
.map(Transaction::getTrader)
.distinct()
.filter(trader -> trader.getCity().equals("Seoul"))
.sorted(Comparator.comparing(Trader::getName))
.forEach(System.out::println);
[문제 4]
모든 거래자의 이름을 순서대로 정렬하라.
transactions.stream()
.map(Transaction::getTrader)
.map(Trader::getName)
.distinct()
.sorted()
.forEach(System.out::println);
[문제 5]
부산에 거래자가 있는지를 확인하라.
boolean isThereTraderInBusan = transactions.stream()
.map(Transaction::getTrader)
.anyMatch(trader -> trader.getCity().equals("Busan"));
System.out.println(isThereTraderInBusan);
[문제 6]
서울에 거주하는 거래자의 모든 거래 내역을 구하라.
transactions.stream()
.filter(transaction -> transaction.getTrader().getCity().equals("Seoul"))
.forEach(System.out::println);
[문제 7]
모든 거래 내역중에서 최댓값과 최솟값을 구하라. 단, 최댓값은 reduce를 이용하고 최솟값은 stream의 min()을 이용하라.
transactions.stream()
.map(Transaction::getValue)
.reduce(Integer::max)
.ifPresent(System.out::println);
transactions.stream()
.map(Transaction::getValue)
.min(Integer::compareTo)
.ifPresent(System.out::println);
5번 문제 모음
[문제 1]
문자열 배열 String[] strArr = {"aaa","bb","c","dddd"}의 모든 문자열의 길이를 더한 결과를 출력하여라.
int sum = Stream.of("aaa", "bb", "c", "dddd")
.mapToInt(String::length)
.sum();
System.out.println(sum);
[문제 2]
문자열 배열 String[] strArr = {"aaa","bb","c","dddd"}의 문자열 중에서 가장 긴 것의 길이를 출력하시오.
int max = Stream.of("aaa", "bb", "c", "dddd")
.mapToInt(String::length)
.max()
.getAsInt();
System.out.println(max);
[문제 3]
임의의 로또번호(1~45)를 정렬해서 출력하시오.
Stream.generate(() -> (int) (Math.random() * 45) + 1)
.distinct()
.limit(6)
.sorted()
.forEach(System.out::println);
[문제 4]
두 개의 주사위를 굴려서 나온 눈의 합이 6인 경우를 모두 출력하시오.
IntStream.rangeClosed(1, 6)
.boxed()
.flatMap(i -> IntStream.rangeClosed(1, 6).mapToObj(j -> Pair.of(i,j)))
.filter(pair -> pair.getLeft() + pair.getRight() == 6)
.forEach(pair -> System.out.println("[" + pair.getLeft() + ", " + pair.getRight() + "]"));
6번 문제 모음
[데이터]
public class Student {
private String name;
private boolean isMale; // 성별
private int hak; // 학년
private int ban; // 반
private int score;
public String toString() {
return String.format("[%s, %s, %d학년 %d반, %3d점 ]", name, isMale ? "남" : "여", hak, ban, score);
}
}
Student[] stuArr = new Student[]{
new Student("나자바", true, 1, 1, 300),
new Student("김지미", false, 1, 1, 450),
new Student("김자바", true, 1, 1, 100),
new Student("이지미", false, 1, 2, 550),
new Student("남자바", true, 1, 2, 200),
new Student("안지미", false, 1, 2, 150),
new Student("황지미", false, 1, 3, 600),
new Student("강지미", false, 1, 3, 350),
new Student("이자바", true, 1, 3, 100),
new Student("나자바", true, 2, 1, 400),
new Student("김지미", false, 2, 1, 50),
new Student("김자바", true, 2, 1, 100),
new Student("이지미", false, 2, 2, 550),
new Student("남자바", true, 2, 2, 600),
new Student("안지미", false, 2, 2, 450),
new Student("황지미", false, 2, 3, 200),
new Student("강지미", false, 2, 3, 100),
new Student("이자바", true, 2, 3, 700)
};
[문제 1]
stuArr에서 불합격(150점 미만)한 학생의 수를 남자와 여자로 구별하여라. (Boolean, List)
Stream.of(stuArr)
.filter(s -> s.getScore() < 150)
.collect(Collectors.partitioningBy(Student::isMale, Collectors.counting()))
.forEach((k, v) -> System.out.println((k ? "남자" : "여자") + " : " + v + "명"));
[문제 2]
각 반별 총점을 학년 별로 나누어 구하여라 (Map<Integer, Map<Integer, Integer>>)
Stream.of(stuArr)
.collect(Collectors.groupingBy(Student::getHak,
Collectors.groupingBy(Student::getBan,
Collectors.summingInt(Student::getScore))))
.forEach((k, v) -> {
System.out.println(k + "학년");
v.forEach((k2, v2) -> System.out.println(k2 + "반 : " + v2 + "점"));
});
“ 좋은 프로그래머 대부분은 돈이나 대중에게 받을 찬사를 기대하고 프로그래밍을 하지 않고 프로그래밍이 재미 있어서 한다. ”
- 리누스 토르발스 (리눅스 창시자)
'Java' 카테고리의 다른 글
한글 Levenshtein Distance 구현 (0) | 2024.12.08 |
---|---|
한글 초성, 중성, 종성 분리하기 (0) | 2024.12.08 |
[Java] 트리 구조 데이터 가져오기 (+SQL) (0) | 2024.07.14 |