How to select duplicate values from a list in java?

后端 未结 13 974
傲寒
傲寒 2021-01-18 00:38

For example my list contains {4, 6, 6, 7, 7, 8} and I want final result = {6, 6, 7, 7}

One way is to loop through the list and eliminate unique values (4, 8 in this

13条回答
  •  半阙折子戏
    2021-01-18 01:14

    Is there any other efficient way rather than looping through list ?

    You could hire a magic elf and let it do it for you. How would you ever want to do this without looping through it? If you don't loop through the list, you even won't be able to have a look at the elements. It is like you want to sum a whole bunch of numbers together without looking at those numbers. Summing elements is much easier than searching for duplicates or searching for unique elements. In general, 97% of what code does is looping through lists and data and process and update it.

    So, said that, you have to loop. Now you might want to choose the most efficient way. Some methods come to mind:

    • Sort all the numbers and then loop only once through it to find duplicates (since they will be next to each other). However, keep in mind that sorting algorithms also loop through the data.
    • For each element in the list, check if there is another element with the same value. (This is how you did it. This means you have two loops inside each other. (contains loops through the list of course.))

提交回复
热议问题