I have a LinkedList that contains many objects. How can I find the number and frequency of the distinct elements in the LinkedList.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can iterate the list with a for-each loop while maintaining a histogram.
The histogram will actually be a
Map<T,Integer>whereTis the type of the elements in the linked list.If you use a HashMap, this will get you
O(n)average case algorithm for it – be sure you overrideequals()andhashCode()for yourTelements. [ifTis a built-in class [likeIntegerorString], you shouldn’t be worried about this, they already override these methods].The idea is simple: iterate the array, for each element: search for it in the histogram – if it is not there, insert it with value 1 [since you just saw it for the first time]. If it is in the histogram already, extract the
value, and re-insert the element – with the same key and withvalue + 1.should look something like this: [
listis of typeLinkedList<Integer>]