-2

A collection is given like - [10,11,5,6,10,11,10,11,10,5]
Answer should contains only last element(if element is repeated)
Answer - [5,10,6,11]
here element(5) is repeated 2 times so answer should contain 2nd 5
similarly element(10) is repeated 4 times so answer should contain 4th 10
element(11) is repeated 3 times so answer should contain 3rd 11
Note : - here number of time of repetition of element is not matters.

Anurag_BEHS
  • 1,390
  • 2
  • 22
  • 36
  • Possible duplicate of [How to maintain a Unique List in Java?](http://stackoverflow.com/questions/13259535/how-to-maintain-a-unique-list-in-java) – px06 Feb 16 '17 at 17:27
  • This question has been asked millions of times and if you google it the first link that comes up is the documentation to [Set](https://docs.oracle.com/javase/7/docs/api/java/util/Set.html). Please research before posting questions. – px06 Feb 16 '17 at 17:28
  • But Set is going to insert 1st element, after that if duplicates are coming it will not add , here my question is i have to save last entry not 1st – Anurag_BEHS Feb 16 '17 at 17:32
  • @Larrykuk You could construct a Map with key = number and value = number of repetitions of that number. Then you can create your endresult list from the entrySet of that map. – OH GOD SPIDERS Feb 16 '17 at 17:35
  • 1
    When you say "last" and "first" I'm going to assume you are receiving an ordered Collection. If that's the case, why not traverse it and use a `Set` anyway? That way it's saving the "last" elements. – px06 Feb 16 '17 at 17:35
  • @px06 From the way I understand him (and the question isn't really clear) he wants to have a sorted list by the number of duplicates. So 10 is his first element because it exists 4 times in the original list, after that 11 with 3 appearances, 5 with 2 and 6 with only 1. When he says "last" i actually think he means "least appearing number"... – OH GOD SPIDERS Feb 16 '17 at 17:39
  • @911DidBush I see what you're saying, this question is very unclear but the solution you have suggested should be sufficient if that's what he's seeking. – px06 Feb 16 '17 at 17:42
  • @px06 solution suggested by you to reverse the order of given collection and use a set to traverse .. this way we can go ......any more way to go ...... – Anurag_BEHS Feb 16 '17 at 18:00

1 Answers1

1

You need to sort the list on the basis of number of repetitions. As @px06 mentioned in the comments you can use set for unique and sorted values. But this will not give you result on the basis of number of repetitions.

Collections.frequency(List, value);

will give the frequency of value in the list. You need to iterate the list and then put the result into new collection.

Atul
  • 1,536
  • 3
  • 21
  • 37