从java中的arraylist中获取唯一值

SDa*_*Das 69 java list set

我有ArrayList一些记录和一个列包含气体名称为CO2 CH4 SO2等.现在我想要检索不同的气体名称(唯一),只是没有重复ArrayList.怎么做到呢?

jah*_*roy 110

你应该使用一套.

Set是一个不包含重复项的Collection.

如果您有一个包含重复项的List,您可以获得如下所示的唯一条目:

List<String> gasList = // create list with duplicates...
Set<String> uniqueGas = new HashSet<String>(gasList);
System.out.println("Unique gas count: " + uniqueGas.size());
Run Code Online (Sandbox Code Playgroud)

注意:此HashSet构造函数通过调用元素的equals()方法来标识重复项.


Geo*_*lou 57

您可以使用Java 8 Stream API.

方法distinct是一个过滤流的中间操作,只允许distict值(默认情况下使用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
Run Code Online (Sandbox Code Playgroud)


Mat*_*arz 11

我希望我能正确理解你的问题:假设值是类型String,最有效的方法可能是转换为a HashSet并迭代它:

ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
   ... //Do something
}
Run Code Online (Sandbox Code Playgroud)


Nit*_*791 7

您可以使用它来使列表唯一

ArrayList<String> listWithDuplicateValues = new ArrayList<>();
list.add("first");
list.add("first");
list.add("second");

ArrayList uniqueList = (ArrayList) listWithDuplicateValues.stream().distinct().collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)


hyd*_*yde 6

这是一种直接的方式,无需使用自定义比较器或类似的东西:

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);
Run Code Online (Sandbox Code Playgroud)

注意:使用TreeSet而不是HashSet直接排序的arraylist和上面Collections.sort可以跳过,但是TreeSet效率更低,所以HashSet即使需要排序,它也常常更好,甚至更糟.


xag*_*gyg 6

ArrayList values = ... // your values
Set uniqueValues = new HashSet(values); //now unique
Run Code Online (Sandbox Code Playgroud)