99 Club 2기 | Java | Beginner
🚩 1773. Count Items Matching a Rule
🏷 관련 주제 : Array String
Easy
You are given an array items, where each items[i] = [$type_{i},\ color_{i},\ name_{i}$] describes the type, color, and name of the $i^{th}$ item. You are also given a rule represented by two strings, ruleKey and ruleValue.
The $i^{th}$ item is said to match the rule if one of the following is true:
ruleKey == "type"andruleValue== $type_{i}$.ruleKey == "color"andruleValue== $color_{i}$.ruleKey == "name"andruleValue== $name_{i}$.
Return the number of items that match the given rule.
Example 1:
Input: items = [["phone","blue","pixel"],["computer","silver","lenovo"],["phone","gold","iphone"]], ruleKey = "color", ruleValue = "silver"
Output: 1
Explanation: There is only one item matching the given rule, which is ["computer","silver","lenovo"].
Example 2:
Input: items = [["phone","blue","pixel"],["computer","silver","phone"],["phone","gold","iphone"]], ruleKey = "type", ruleValue = "phone"
Output: 2
Explanation: There are only two items matching the given rule, which are ["phone","blue","pixel"] and ["phone","gold","iphone"]. Note that the item ["computer","silver","phone"] does not match.
Constraints:
1 <= items.length <= 1041 <= typei.length, colori.length, namei.length, ruleValue.length <= 10ruleKeyis equal to either"type","color", or"name".- All strings consist only of lowercase letters.
Accepted 223.6K | Submissions 263.4K | Acceptance Rate 84.9%
✔ Solution with Loop
class Solution {
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
String[] keys = {"type", "color", "name"};
int answer = 0;
for (int i = 0; i < 3; i++) {
if (keys[i].equals(ruleKey)) {
for (int j = 0; j < items.size(); j++) {
if (items.get(j).get(i).equals(ruleValue)) {
answer++;
}
}
break;
}
}
return answer;
}
}
채점 결과

✔ Solution with List & Stream API
import java.util.Arrays;
import java.util.List;
class Solution {
int idx = -1;
public int countMatches(List<List<String>> items, String ruleKey, String ruleValue) {
List<String> keys = Arrays.asList("type", "color", "name");
idx = keys.indexOf(ruleKey);
int answer = items.stream().filter(li -> li.get(idx).equals(ruleValue)).collect(Collectors.toList()).size();
return answer;
}
}
채점 결과

💥 오늘 만난 문제 & 나의 시도 💦 & 해결 방법 👍
LeetCode에 업로드한 풀이 (링크🔗)
📌 오늘 만난 문제 : 매개변수로 받은 List<List<Integer>> items에 대하여
items[i] = [ $type_{i},\ color_{i},\ name_{i}$ ] 는item의 i번째 원소의 type, color, name을 나타냅니다.
그리고 또 다른 매개변수로 주어진 2가지 규칙 ruleKey, ruleValue에 대하여items의 i번째 item은 다음의 성질 중 하나를 만족한다.
ruleKey가 "type"이고ruleValue는 $type_{i}$ruleKey가 "color"이고ruleValue는 $color_{i}$ruleKey가 "name"이고ruleValue는 $name_{i}$
매개변수로 받은 규칙과 일치하는 item의 개수를 반환하시오.
반복문과 List의 기본 메서드를 이용해 탐색해야할 Key의 인덱스를 찾고 ruleValue와 일치하는 원소의 개수를 세어 반환하자.
1. 반환할 값을 담을 변수 answer 초기화
int answer = 0;
2. 탐색해야할 Key의 인덱스를 찾기 위해 이용할 keys를 Key의 종류 "type", "color, "name"을 원소로 갖는 문자열 배열로 초기화하자.
String[] keys = {"type", "color", "name"};
3. 반복문을 통해 Key의 인덱스를 찾자.
for (int i = 0; i < 3; i++) {
if (keys[i].equals(ruleKey)) {...}
}
4. 반복문을 통해 List의 ruleKey에 해당하는 인덱스의 원소를 탐색하고 그 값이 ruleValue와 일치하면 answer의 값을 1 증가
if (items.get(j).get(i).equals(ruleValue)) {
answer++;
}
💬 무엇을 새롭게 알았는지
- 다양한 방법으로 문제를 풀어보았다.
- List 객체에 원소를 담아 생성하는 법을 알게 되었다.
Arrays.toList(원소1, 원소2, ...) - List의 메서드를 사용해 보았다.
get()indexOf()size() - 문자열 비교 :
equals() - Stream API를 사용해 보았다.
📚 References(참고 자료)
[JAVA] 리스트(List) 정렬: Collections.sort() 코드를 뜯어보았다, Comparable
[Java/Kotlin] 자바 Stream을 통해 리스트의 요소를 특정 key 기준으로 grouping하여 다른 객체로 합치기 및 코틀린으로 변경해보기
Java의 List를 상황에 맞게 생성해보자 ( asList(), emptyList(), singletonList() )