-1

I have a list for user IDs. It consists of user IDs selected from different tables, so there are duplicate IDs in it. How can I only select unique IDs from this list or possibly remove duplicates?

List < userDto > list = uC.match(dto2);
if (list.size() > 0) {
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.size());
        System.out.println("Data Found");

        userDto dto3 = new userDto();
        dto3 = uC.get(list.get(i));

        System.out.println(dto3.firstName);
    }
} else {
    System.out.println("Data not Found");
}

I edited as below it shows the same result as List..I am new to this. I don't know whats wrong.. please help

Set<userDto> list = new HashSet<userDto>(uC.match1(dto2));

    if(list.size()>0){
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.size());
        userDto dto3=new userDto();
        for (userDto s : list) {
            dto3=uC.get(s);
        }
        System.out.println(dto3.firstName);
        }
    }
  • The question doesn't appear to include any attempt at all to solve the problem. Please edit the question to show what you've tried, and show a specific roadblock you're running into with [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). For more information, please see [How to Ask](https://stackoverflow.com/help/how-to-ask). – Andreas Oct 22 '19 at 04:29
  • Possible duplicate of [Get unique values from arraylist in java](https://stackoverflow.com/questions/13429119/get-unique-values-from-arraylist-in-java) – sovannarith cheav Oct 22 '19 at 04:31

3 Answers3

1

add them all to a set that is what a Set does

mavriksc
  • 1,130
  • 1
  • 7
  • 10
  • It didn't work. Don't know why? What i am doing is.... adding random(consists multiple) data into set.. And when i want to use it I do not want duplicate data. It gives the same result as LIST. –  Oct 22 '19 at 08:30
  • you need to implement comparable on the objects otherwise the default behaviour is to just compare their memory locations and class type – mavriksc Oct 22 '19 at 13:37
  • instead of comparable i meant override equals() on your dto object – mavriksc Oct 22 '19 at 15:08
0

Use set for unique values.

 Set<userDto> hSet = new HashSet<userDto>(list); 
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42
0

Instead of List you can use Set as set stores unique elements. Also you can convert List to Set

 Set<userDto> list=new HashSet<userDto>(uC.match(dto2));
Gaurav Dhiman
  • 953
  • 6
  • 11