Java의 ArrayList에서 원하는 값 가져오기
나는 가지고 있다.ArrayList
CO2 CH4 SO2 등의 가스 이름을 포함하는 여러 개의 기록과 함께 한 열에 포함되어 있습니다.이제 다른 가스 이름(고유)만 불러오고 싶다.ArrayList
어떻게 할 수 있을까요?
A를 사용해야 합니다.Set
는 중복되지 않는 컬렉션입니다.
중복이 포함된가 있는 경우 다음과 같은 고유한 엔트리를 얻을 수 있습니다.
List<String> gasList = // create list with duplicates...
Set<String> uniqueGas = new HashSet<String>(gasList);
System.out.println("Unique gas count: " + uniqueGas.size());
주의: 이 항목입니다.HashSet
컨스트럭터는 요소의 equal() 메서드를 호출하여 중복을 식별합니다.
Java 8 Stream API를 사용할 수 있습니다.
method distinate는 스트림을 필터링하여 (기본적으로 Object:: equals 메서드를 사용하여) 고유한 값만 다음 조작에 전달할 수 있는 중간 조작입니다.
저는 당신의 사례를 아래에 적었습니다.
// Create the list with duplicates.
List<String> listAll = Arrays.asList("CO2", "CH4", "SO2", "CO2", "CH4", "SO2", "CO2", "CH4", "SO2");
// Create a list with the distinct elements using stream.
List<String> listDistinct = listAll.stream().distinct().collect(Collectors.toList());
// Display them to terminal using stream::collect with a build in Collector.
String collectAll = listAll.stream().collect(Collectors.joining(", "));
System.out.println(collectAll); //=> CO2, CH4, SO2, CO2, CH4 etc..
String collectDistinct = listDistinct.stream().collect(Collectors.joining(", "));
System.out.println(collectDistinct); //=> CO2, CH4, SO2
제가 당신의 질문을 올바르게 이해하기를 바랍니다: 값이 유형이라고 가정합니다.String
, 가장 효율적인 방법은, 아마, 로 변환하는 것입니다.HashSet
그리고 그것을 반복한다:
ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
... //Do something
}
목록을 고유하게 만드는 데 사용할 수 있습니다.
ArrayList<String> listWithDuplicateValues = new ArrayList<>();
list.add("first");
list.add("first");
list.add("second");
ArrayList uniqueList = (ArrayList) listWithDuplicateValues.stream().distinct().collect(Collectors.toList());
ArrayList values = ... // your values
Set uniqueValues = new HashSet(values); //now unique
커스텀 컴퍼레이터 등에 의존하지 않는 간단한 방법은 다음과 같습니다.
Set<String> gasNames = new HashSet<String>();
List<YourRecord> records = ...;
for(YourRecord record : records) {
gasNames.add(record.getGasName());
}
// now gasNames is a set of unique gas names, which you could operate on:
List<String> sortedGasses = new ArrayList<String>(gasNames);
Collections.sort(sortedGasses);
주의: 사용방법TreeSet
대신HashSet
직접 정렬된 배열 목록 이상을 제공합니다.Collections.sort
생략할 수 있지만TreeSet
그렇지 않으면 효율이 떨어지기 때문에 대부분의 경우 더 좋고 더 나쁜 경우는 거의 없습니다.HashSet
정렬이 필요한 경우에도 마찬가지입니다.
같은 질문을 했을 때, 이전의 답변은 모두 좋은 통찰력을 가지고 있었지만, 제 사례에 대한 솔루션을 조정하는 데 어려움을 겪었습니다.
다음은 문자열이 아닌 고유한 개체 목록을 획득해야 하는 경우의 해결책입니다.예를 들어 Record 객체의 목록이 있다고 합시다. Record
클래스에는 유형의 속성만 있습니다.String
, 유형의 속성이 없습니다.int
여기에서는, 실장hashCode()
로서 어려워지다hashCode()
반환할 필요가 있다int
.
다음은 샘플입니다.Record
학급.
public class Record{
String employeeName;
String employeeGroup;
Record(String name, String group){
employeeName= name;
employeeGroup = group;
}
public String getEmployeeName(){
return employeeName;
}
public String getEmployeeGroup(){
return employeeGroup;
}
@Override
public boolean equals(Object o){
if(o instanceof Record){
if (((Record) o).employeeGroup.equals(employeeGroup) &&
((Record) o).employeeName.equals(employeeName)){
return true;
}
}
return false;
}
@Override
public int hashCode() { //this should return a unique code
int hash = 3; //this could be anything, but I would chose a prime(e.g. 5, 7, 11 )
//again, the multiplier could be anything like 59,79,89, any prime
hash = 89 * hash + Objects.hashCode(this.employeeGroup);
return hash;
}
다른 사람들이 앞서 제안했듯이 클래스는 두 가지 요소를 모두 덮어쓸 필요가 있습니다.equals()
및 그hashCode()
사용할 수 있는 방법HashSet
.
예를 들어, 기록 목록은allRecord
(List<Record> allRecord
).
Set<Record> distinctRecords = new HashSet<>();
for(Record rc: allRecord){
distinctRecords.add(rc);
}
이렇게 하면 해시 집합, distinent Records에만 고유 레코드가 추가됩니다.
이게 도움이 됐으면 좋겠다.
public static List getUniqueValues(List input) {
return new ArrayList<>(new LinkedHashSet<>(incoming));
}
먼저 동등한 방법을 구현하는 것을 잊지 마십시오.
특정 종류의 객체(bean) 배열이 있는 경우 다음을 수행할 수 있습니다.
List<aBean> gasList = createDuplicateGasBeans();
Set<aBean> uniqueGas = new HashSet<aBean>(gasList);
위의 마티아스 슈바르츠처럼, 하지만 당신은 당신의 aBean에게 방법을 제공해야 합니다.hashCode()
★★★★★★★★★★★★★★★★★」equals(Object obj)
메뉴인 '이클립스'에서 할 수 .Generate hashCode() and equals()
(bean)Set은 동일한 개체를 식별하기 위해 재정의된 메서드를 평가합니다.
언급URL : https://stackoverflow.com/questions/13429119/get-unique-values-from-arraylist-in-java
'programing' 카테고리의 다른 글
Laravel Echo 접속, 절단, 재접속 등의 처리방법 (0) | 2022.11.26 |
---|---|
java.sql.SQLException: - ORA-01000: 열려 있는 최대 커서 수를 초과했습니다. (0) | 2022.11.26 |
정적 변수는 언제 초기화됩니까? (0) | 2022.11.26 |
루트 액세스 없이 python 모듈을 설치하는 방법 (0) | 2022.11.26 |
Python 스크립트를 실행하지 않고 어떻게 구문을 확인할 수 있습니까? (0) | 2022.11.26 |