How to find duplicate elements in array in effective way. I mean to say with very less iterations
<?php
Using Characters here, as give more flexibility.
Character[] arrayC= (new Character[] { 'a', 'a', 'a', 'b', 'b' ,'v'});
List<Character> allChars= new ArrayList<>(Arrays.asList(arrayC));
List<Character> duplicates = allChars.stream().distinct().filter(
entry -> Collections.frequency(allChars, entry) > 1).
collect(Collectors.toList());
// duplicates --> 'a','b'
First the array is converted into an ArrayList. Then, if finds some entry that is repeated more than once, it collects it into duplicates.
If you want to get which are not duplicates, just:
allChars.removeAll(duplicates);
0 comments:
Post a Comment
Thanks