반응형
Map을 사용할 수도 있고, 다른 여러가지 자료형을 통해 중복값을 제거하는 방법은 많다.
여기서는 ArrayList를 다룰때, 중복값을 제거하고 그 제거한 값의 원래 개수를 리턴하는 메서드를 다룬다.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
ArrayList<String> inputList = new ArrayList<>();
inputList.add("apple");
inputList.add("orange");
inputList.add("apple");
inputList.add("banana");
inputList.add("orange");
inputList.add("apple");
ArrayList<String> resultList = removeDuplicatesAndCount(inputList);
System.out.println(resultList);
}
public static ArrayList<String> removeDuplicatesAndCount(ArrayList<String> inputList) {
ArrayList<String> resultList = new ArrayList<>();
HashMap<String, Integer> countMap = new HashMap<>();
for (String element : inputList) {
countMap.put(element, countMap.getOrDefault(element, 0) + 1);
}
for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
resultList.add(entry.getKey() + " - " + entry.getValue());
}
return resultList;
}
}
위 코드를 실행하면, 요소의 대표값인 apple, orange, banana 값만 남고 중복제거 하기 전 개수인 3,2,1 리턴된다.
결과는 다음과 같다.
[apple - 3, orange - 2, banana - 1]
반응형
'Programing > JAVA' 카테고리의 다른 글
String 문자열에서 줄바꿈을 기준으로 특정문자가 포함된 라인 제거 (0) | 2023.04.21 |
---|---|
swing 을 이용하여 윈도우 gui 만들고, 로깅하기 (0) | 2023.04.20 |
java POi 이용해서 피벗차트 만들기 (0) | 2023.04.17 |
intelliJ에서 build하는 법 (0) | 2023.04.12 |
java Calendar / SimpleDateFormat 이용하여 여러 날짜 형식 구하기 (0) | 2021.05.27 |