이전 작성 코드에서
1. 입력된 순서는 현재 문재에서 필요 없으므로 LinkedHashSet을 HastSet으로 개선
2. Map.getOrDefault() 활용하여 if문 줄이며 코드 간결화
3. 반복문에 Map.entrySet(), Map.Entry 자료형 활용
4. java collection Stream 기능 활용
// 한 유저가 동일한 유저 신고했을 때 카운트 1회로 처리해야 함
// 특정 유저가 n번 이상 신고되었을때 그 신고한 유저에게 메일 보내야 함.
import java.util.*;
class Solution {
public int[] solution(String[] id_list, String[] report, int k) {
int[] answer = {};
HashSet<String> hashSet = new HashSet<>(Arrays.asList(report));
HashMap<String, Set<String>> reportIdList_Id = new HashMap<String, Set<String>>();
HashMap<String, Integer> reportId_reportCnt = new HashMap<String, Integer>();
for(String i : hashSet){
String[] i_r = i.split(" ");
String id = i_r[0];
String report_id = i_r[1];
// if(reportId_reportCnt.containsKey(report_id) == false){
// reportId_reportCnt.put(report_id, 1);
// }else{
// reportId_reportCnt.put(report_id, reportId_reportCnt.get(report_id) +1);
// }
reportId_reportCnt.put(report_id, reportId_reportCnt.getOrDefault(report_id, 0) + 1);
// if(reportIdList_Id.containsKey(report_id) == false){
// List<String> arr = new ArrayList<String>();
// arr.add(id);
// reportIdList_Id.put(report_id, arr);
// }else{
// List<String> arr = reportIdList_Id.get(report_id);
// arr.add(id);
// reportIdList_Id.put(report_id, arr);
// }
Set<String> arr = reportIdList_Id.getOrDefault(report_id, new HashSet<String>());
arr.add(id);
reportIdList_Id.put(report_id, arr);
}
// reportIdList_Id에서 k번 이상 신고당한 사람 걸러내기 위하여 수행한 부분
List<String> list = new ArrayList<String>();
reportId_reportCnt.forEach((key,value)->{
if(value<k){
list.add(key);
}
}
);
for(String s : list){
reportIdList_Id.remove(s);
}
Map<String, Integer> countMap = new LinkedHashMap<>();
for (String id : id_list) {
countMap.put(id, 0);
}
for (Map.Entry<String, Set<String>> entry: reportIdList_Id.entrySet()){
for(String value : entry.getValue()){
countMap.put(value, countMap.getOrDefault(value, 0) + 1);
}
}
//return countMap.values().stream().mapToInt(i->i).toArray();
// 람다식 사용하는 방법
//return countMap.values().stream().mapToInt(i->Integer.valueOf(i)).toArray();
// 1. mapToInt에 메서드 참조를 이용하는 방법
return countMap.values().stream().mapToInt(Integer::intValue).toArray();
// int[] ans = new int[id_list.length];
// int index = 0;
// for(String i : id_list){
// int count = 0;
// for(String key : reportIdList_Id.keySet()){
// if(reportIdList_Id.get(key).contains(i))
// count++;
// }
// ans[index++]= count;
// }
// return ans;
}
}
댓글