[람다 스트림] [문자열] [자바] [백준] - 20920 영단어 암기는 괴로워

SlowAnd·2024년 1월 16일
0

Map 정렬을 연습할 수 있는 문제다.

https://www.acmicpc.net/problem/20920

package boj.String;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
import java.util.stream.Collectors;

public class boj_20920 {
    public static void main(String[] args) throws IOException {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
        List<Integer> collect = Arrays.stream(r.readLine().split(" ")).map(Integer::parseInt)
                .collect(Collectors.toList());
        int N = collect.get(0);
        int M = collect.get(1);

        List<String> words = new ArrayList<>();
        for (int i = 0; i < N; i++) {
            words.add(r.readLine());
        }

        List<String> sortedWords = words.stream()
                .filter(word -> word.length() >= M)
                .collect(Collectors.groupingBy(word -> word, Collectors.counting()))
                .entrySet().stream()
                .sorted(Map.Entry.<String, Long>comparingByValue(Comparator.reverseOrder())
                        .thenComparingInt(e -> -e.getKey().length())
                        .thenComparing(Map.Entry.comparingByKey()))

                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

        for(String sortedWord : sortedWords){
            w.write(sortedWord);
            w.newLine();
        }
        w.flush();
    }
}

0개의 댓글