Sumit Singh :
I am taking a sorted array with some duplicate values and then to simply remove duplicity, I am adding each value into the set. As I am creating a set from a sorted array, why I am not getting a sorted set?
Here is my code:
Set<Integer> set = new HashSet<Integer>();
for(int score: scores)
if(!(set.contains(score)))
set.add(score);
System.out.println(set);
The vale of scores is 100 100 50 40 40 20 10
Expected output: [100, 50, 40, 20, 10]
Actual output: [50, 100, 20, 40, 10]
Trishul Singh Choudhary :
I see you're doing if(!(set.contains(score)))
this comparison. Then why not go for a list ? List will maintain the insertion order.
int scores[]= {100,100,50,40,40,20,10};
List<Integer> list=new ArrayList<Integer>();
for(int score: scores)
if(!(list.contains(score)))
list.add(score);
System.out.println(list);
}
Output ::
[100, 50, 40, 20, 10]