多数のレコードがArrayList
あり、1 つの列に CO2 CH4 SO2 などのガス名が含まれていますArrayList
。. どうすればそれができますか?
9 に答える
を使用する必要がありますSet
。ASet
は、重複を含まないコレクションです。
重複を含むがある場合はList
、次のように一意のエントリを取得できます。
List<String> gasList = // create list with duplicates...
Set<String> uniqueGas = new HashSet<String>(gasList);
System.out.println("Unique gas count: " + uniqueGas.size());
注: このコンストラクターは、要素のequals()HashSet
メソッドを呼び出して重複を識別します。
Java 8 Stream APIを使用できます。
Distinct メソッドは、ストリームをフィルタリングし、(デフォルトでは 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
あなたの質問を正しく理解していることを願っています: 値が typeString
であると仮定すると、最も効率的な方法はおそらく a に変換してHashSet
それを反復処理することです:
ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
... //Do something
}
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
と、直接並べ替えられた arraylist が得られ、上記Collections.sort
はスキップできますが、それ以外の場合は効率が低下するため、並べ替えが必要な場合でもTreeSet
使用する方が良いことが多く、悪いことはめったにありません。HashSet
これを使用して、リストを一意にすることができます
ArrayList<String> listWithDuplicateValues = new ArrayList<>();
list.add("first");
list.add("first");
list.add("second");
ArrayList uniqueList = (ArrayList) listWithDuplicateValues.stream().distinct().collect(Collectors.toList());
同じクエリを実行していたとき、以前のすべての回答には優れた洞察がありましたが、ソリューションを自分のケースに合わせるのに苦労しました.
文字列ではなく、一意のオブジェクトのリストを取得する必要がある場合の解決策を次に示します。たとえば、Record オブジェクトのリストがあるとします。Record
class には type のプロパティのみがあり、 type のプロパティはありませ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);
}
これは、個別のレコードのみをハッシュセット、個別のレコードに追加します。
お役に立てれば。
ある種のオブジェクト (Bean) の配列がある場合、これを行うことができます。
List<aBean> gasList = createDuplicateGasBeans();
Set<aBean> uniqueGas = new HashSet<aBean>(gasList);
上記のMathias Schwarzが言ったように、aBeanにメソッドを提供する必要があり、これhashCode()
はEclipseで専用メニュー「 」(beanクラス内)でequals(Object obj)
簡単に実行できます。Generate hashCode() and equals()
Set は、オーバーライドされたメソッドを評価して、等しいオブジェクトを識別します。