I have an ArrayList
with a number of records and one column contains gas names as CO2 CH4 SO2 etc.Now i want to retrieve different gas names(unique) only without repetation from the ArrayList
. How can it be done?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
When I was doing the same query, I had hard time adjusting the solutions to my case, though all the previous answers have good insights.
Here is a solution when one has to acquire a list of unique objects, NOT strings. Let's say, one has a list of Record object.
Record
class has only properties of typeString
, NO property of typeint
. Here implementinghashCode()
becomes difficult ashashCode()
needs to return anint
.The following is a sample
Record
Class.As suggested earlier by others, the class needs to override both the
equals()
and thehashCode()
method to be able to useHashSet
.Now, let's say, the list of Records is
allRecord
(List<Record> allRecord
).This will only add the distinct Records to the Hashset, distinctRecords.
Hope this helps.
If you have an array of a some kind of object (bean) you can do this:
like said Mathias Schwarz above, but you have to provide your aBean with the methods
hashCode()
andequals(Object obj)
that can be done easily in Eclipse by dedicated menu 'Generate hashCode() and equals()
' (while in the bean Class). Set will evaluate the overridden methods to discriminate equals objects.You can use Java 8 Stream API.
Method distinct is an intermediate operation that filters the stream and allows only distict values (by default using the Object::equals method) to pass to the next operation.
I wrote an example below for your case,
you can use this for making a list Unique
dont forget to implement your equals method