How could I go about detecting (returning true/false) whether an ArrayList contains more than one of the same element in Java?
Many thanks, Terry
Edit Forgot to mention that I am not looking to compare "Blocks" with each other but their integer values. Each "block" has an int and this is what makes them different. I find the int of a particular Block by calling a method named "getNum" (e.g. table1[0][2].getNum();
I needed to do a similar operation for a
Stream
, but couldn't find a good example. Here's what I came up with.This has the advantage of short-circuiting when duplicates are found early rather than having to process the whole stream and isn't much more complicated than just putting everything in a
Set
and checking the size. So this case would roughly be:Improved code, using return value of
Set#add
instead of comparing the size of list and set.Improved code to return the duplicate elements
Simply put: 1) make sure all items are comparable 2) sort the array 2) iterate over the array and find duplicates