0

I have two arrayLists namely readAllNames and anotherone is selectedNames.now i want to get the anotherlist which having the unSelectedNames .ex.

List<Name>readAllNames = {"a","b","c","d","e","f","g"};
List<Name>selectedNames = {"a","b"};

how can i get the: unSelectedNames {"c","d","e","f","g"} from readAllNames?

without Using remove() And removeAll()

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
Arunprasad
  • 567
  • 4
  • 14
  • 29

6 Answers6

3
List<String> unread = new ArrayList<String>();
for(String s : readAllNames ){
    if(!selectedNames.contains(s))
        unread.add(s);
}
Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
spiritwalker
  • 2,257
  • 14
  • 9
  • but Have to do override also http://stackoverflow.com/questions/2642589/how-does-a-java-arraylist-contains-method-evaluate-objects – Arunprasad Feb 01 '13 at 14:32
2

If you don't want to use remove()/removeAll() you could always iterate through readAllNames and for each element check if it is contains()'ed in selectedNames and if not add it to unselectedNames.

But you really should use removeAll(); show us your Name class and we can probably tell you what's wrong (hint: read up on equals() and hashCode() semantics wrt. Collection operations.)

Cheers,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
0

Why not take a look at the sourcecode for remove() and use that?

  • bcz '@PostConstruct' method remove() and removeAll() not working properly.but those are working in junit test perfectly.i don't know the reason . – Arunprasad Feb 01 '13 at 12:49
  • 1
    Sorry I don't understand your response. remove() will definitely do what you want it to do. If it's not working then it's an issue with your data or parameters. –  Feb 01 '13 at 12:50
  • 1
    This is probably because your Name class has not implemented equals / hashcode methods properly. – ditkin Feb 01 '13 at 12:52
0
ArrayList<Name> unselectedName = new ArrayList<String>();
for(Name s: readAllNames){
    if(!selectedNames.contains(s)){
        unselectedName.add(s);
    }
}
altsyset
  • 339
  • 2
  • 20
0

Try this:

List<String> unSelectedNames = new ArrayList<String>(readAllNames);
unSelectedNames.removeAll(selectedNames);

You don't have to touch the original List, just the copy of that.

gaborsch
  • 15,408
  • 6
  • 37
  • 48
0

try this

List<Name>readAllNames = {"a","b","c","d","e","f","g"};
List<Name>selectedNames = {"a","b"};
List<Name>unselectedNames = null;
Collections.copy(unselectedNames , readAllNames);
unselectedNames.removeAll(selectedNames);
Srihari
  • 766
  • 1
  • 6
  • 22