Reputation: 45
I have a variable length Collection full of one letter strings (it can be any type of collection). I am trying to create a result based on what the collection contains. If all of the letters in the collection are "P" then the result is "P", if all of the letters are "N" then the result is "N", if there is a mix of the two then the result is "NC". Is there anyway to do this without creating a complicated mess of loops? Thank you for your help.
Upvotes: 0
Views: 332
Reputation: 7625
Yes you could use:
Collections.frequency(f, "N");
Just like this:
String n = "N";
Collection f = new ArrayList();
f.add(n);
f.add(n);
f.add(n);
f.add(n);
System.out.println(Collections.frequency(f, n));
Upvotes: 5
Reputation: 2661
you could convert the collection to a set, then each element will only occur once, and you can just loop through the set to collect an single instance of each entry (ie, ever element that was in the collection will occur exactly once within the set).
I believe
Set newSet = new HashSet(existingCollection)
will work for that
Upvotes: 0