0

I have a set, i.e

Set<FitmentData> fitmentDataSet;

this set has around 5 objects.

public class FitmentData implements Comparable<FitmentData> 
{
private String year;
private String make;
private String model;

}

Now, I need to iterate through this set and find out how many different vehicles this set has comparing year,make and model.I was thinking to get the first object and loop through set by comparing year, make, model. Is there a better way to deal this?

Note: My sample fitment object looks like

new FitementDate("2005", "honda","crv" );
new FitementDate("2005", "honda","crv" );
new FitementDate("2005", "honda","crv" );
new FitementDate("2005", "mazda","cx-5" );
new FitementDate("2005", "subaru","forester" );
Nadim Baraky
  • 459
  • 5
  • 18
karim
  • 29
  • 1
  • 4
  • If you are using Java 8, refer to Stream API - groupBy() – Andrii Abramov Nov 15 '16 at 17:17
  • 4
    If you implemented `equals` and `hashCode` correctly, there would only be three items in the set. – Makoto Nov 15 '16 at 17:17
  • 1
    set don't keep duplicate values, try `List` instead – bananas Nov 15 '16 at 17:19
  • What implementation of `Set` do you use? A custom one? As @Flying Zombie noted, a Set shouldn't provide support for duplicates unless it is mentioned/choosen for explicitly – n247s Nov 15 '16 at 17:35
  • thank you guys, my intention is to take different vehicles into another list or set. – karim Nov 15 '16 at 19:09
  • @n247s, @Flying Zombie : Set can't handle duplicity unless `hashCode` and `equals` is correctly implemented on object (as pointed out by Makoto) – rkosegi Nov 15 '16 at 19:09

1 Answers1

0

As mentioned in the comments: "A set does not contain duplicates", e.g., if you are using a HashSet and you implement the hashCode and equals method correctly. If you are using a TreeSet you also have to implement the compareTo method correctly (and implement the Comparable interface). Regarding the implementation of these methods have a look at other StackOverflow posts (there are many more):

The iteration through the Set (or any Collection) can be done using different approaches: for, foreach, lambda, ...:

Community
  • 1
  • 1
Philipp
  • 1,289
  • 1
  • 16
  • 37
  • A set does not contain duplicates true. objects inside a set can have same data(mycase). let me tell you my requirement again. i just want objects from set which has different year, make and model.thanks in advance. – karim Nov 15 '16 at 20:05
  • If you don't have a `Set` in a Java sense, maybe you should talk and use a `List`? And then use the iterations mentioned in http://stackoverflow.com/questions/12455737/how-to-iterate-over-a-set-hashset-without-a-iterator, because these work for all Java `Collections`. – Philipp Nov 15 '16 at 20:09