comparing the elements in a list

for instance i have two list lista and listb. how can i compare the elements in it? like if lista has the name "janu" and listb also have the name "janu" it should say duplicate found. i have compared strings but never compared list. any idea on how to achieve it?
[271 byte] By [lrngjavaa] at [2007-11-27 6:46:54]
# 1
do i compare with the getter methods of the two list?
lrngjavaa at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 2

> for instance i have two list lista and listb. how can

> i compare the elements in it? like if lista has the

> name "janu" and listb also have the name "janu" it

> should say duplicate found. i have compared strings

> but never compared list. any idea on how to achieve

> it?

If you had two sheets of paper, each with a long list of strings on it, how would you compare those for duplicates?

kevjavaa at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 3
iterate through the elements with a for each loop if a match is find then return 1 else -1
lrngjavaa at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 4
Actually, the answer is simpler than we thought: [url= http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html#retainAll(java.util.Collection)] http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html#retainAll(java.util.Collection)[/url]
kevjavaa at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 5

If the lists are unsorted then yes two for loops are needed.

If the lists are sorted though... you can do it in one combined loop.

The difference would be that for two unsorted lists each with 10 elements there is a possibility of 100 comparisons to do. With two sorted lists each again with 10 elements the worst case scenario is 20 comparisons.

cotton.ma at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 6
good allrite thanks for the explanation let me program it.
lrngjavaa at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 7

ok i am able to compare the elements of two list. here is the question

Q) write a method to find out if there is an element in the 2nd list that is an element of the first list.

i created a method public boolean retainAll(List xyz). so now when i call this method it gives me an answer true if there is an element and false if there is no duplicates. Does the question requires me to print the duplicates also ? or just to compare whether duplicates exist or not.

Thanks

lrngjavaa at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 8
We didn't set the homework, why are you asking us?
floundera at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 9
well i was just making sure to see if i am on the right track with this question.
lrngjavaa at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 10
no worries. i will print out the duplicates just incase.
lrngjavaa at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 11
No! Don't guess what you have to do. If you are not sure, go and ask your teacher. If your program doesn't perform as to their expectations you will lose points For not doing stuff as well as doing stuff that isn't required.
floundera at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 12
well the teacher cannot deduct points why? because the question is asking to write a method to see if lista and listb contains any duplicates. so there are only 2 senarios either true/false or print the duplicates. if i do both i wont loose marks i might get some extra credit
lrngjavaa at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 13

> No! Don't guess what you have to do. If you are not

> sure, go and ask your teacher.

Actually since the interpretation of vague emotional statements offered in lieu of actual requirements are what I for one spend most of my time doing it might be good to get into the practice now.

Tip: When cornered for failing to meet said "requirements" lean back, sigh heavily and start talking about limitations in any of the following: TCP, clustered indexes, SMTP, multiple inheiritance. The person who gave you the requirements will be so glad to escape from the mind-numbing vortex that you create that they will quickly forgive and forget.

cotton.ma at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 14

> well the teacher cannot deduct points why? because

> the question is asking to write a method to see if

> lista and listb contains any duplicates. so there are

> only 2 senarios either true/false or print the

> duplicates. if i do both i wont loose marks i might

> get some extra credit

That's the spirit. "I don't care about clarifying the specs. I do as I **** well please". Try keeping your job with that attitude.

floundera at 2007-7-12 18:19:20 > top of Java-index,Java Essentials,New To Java...
# 15

////////SPOILER ALERT--\\\\\\\\\\\\\\\\\\\\

THIS IS HOW I WOULD WRITE THE PROGRAM

You clould also add the lists to a HashSet and use

Iterator it = listb.iterator();

Set comp = new HashSet(lista);

ArrayList ar = new list();

while(it.hasNext())

{

Object a = (Object)it.next

if(!comp.add(a))

{

ar.add(a);

}

}

for(int i=0; i<listc.length;i++)

{

ar.get(i)

}

>

xpyro_666xa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 16
lol cotton. i got it. Positive attitude to work or assignment is always a good sign.
lrngjavaa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 17
wtf. your implementation is ridiculous and does not make any sense. xport
lrngjavaa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 18

How so.....A set does not except add dplicates, so this would work.

and the add method for a set will return false if it does not add the value, and it will return true if it does.

what does not make sense

edit... when I declair ArrayList ar = new list();

I meant to put new ArrayList();

]

xpyro_666xa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 19
yes i know set does not allow duplicates. i could have done that also. but my question is to compare two list not by converting a list into set.
lrngjavaa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 20
I think what xpyro is pointing out is that if add method returns false, then that item must already be in the set and therefore you have a duplicate.
floundera at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 21
right i understood what he said. i mean i can do that easily also not a problem. as i have posted the question i dont know if she want me to use set or sort it. i am just confused right now. retainAll method is returning true all the time. i wonder why.
lrngjavaa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 22
Set Intersection http://java.sun.com/docs/books/tutorial/collections/interfaces/set.html
TuringPesta at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 23

Mr Pest. Thanks for the URL. i know about intersection and union. may be my question is too vague. i know set does not allow duplicates.

import java.awt.Color;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Set;

import java.util.*;

public class MapTester

{

public static void main(String[] args)

{

Map<String, Color> favoriteColors

= new HashMap<String, Color>();

favoriteColors.put("Juliet", Color.PINK);

favoriteColors.put("Romeo", Color.GREEN);

favoriteColors.put("Adam", Color.BLUE);

favoriteColors.put("Eve", Color.PINK);

favoriteColors.put("Eve", Color.PINK);

Set<String> keySet = favoriteColors.keySet();

for (String key : keySet)

{

Color value = favoriteColors.get(key);

System.out.println(key + "->" + value);

}

Set set = new TreeSet(keySet);

System.out.println(set);

}

}

But my question is that is there a way to compare 2 list. someone posted a url for retainAll method but its returning true all the time.

like for eg

String id[] = {"Adam", "eve", "Juliet"};

String id1[] = {"Adam", "sony", "pana"};

List a = new ArrayList();

List b = new ArrayList();

for(int i=0; i<id.length; i++)

a.add(id[i]);

for(int i=0; i><id1.length; i++)

b.add(id1[i]);

Now i would like to compare my 2 list to see if there are duplicates or not, rather than converting my list to set is there any other way?

so i tried this

a.retainAll(b);

this returns true whether there is a duplicate or not.

Message was edited by:

lrngjava>

lrngjavaa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 24

as I posted befor that method I posted would compare, and then all of he duplicates will be in the array list.

however, if you would like to do it another way, however in eficcient you could use a nested for loop.

use the String method equals(String)

public boolean isDupe(list lista, list listb)

{

for(int i=0;i<lista.length;i++)

{

for(int j=0;j<listb.length;j++)

{

String a = (String)lista.get(i);

string b= (String)listb.get(j);

if(a.equals(b))

return true;

}

}

return false;

}

Message was edited by:

xpyro_666x>

xpyro_666xa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 25

> Mr Pest. Thanks for the URL. i know about

> intersection and union. may be my question is too

> vague. i know set does not allow duplicates.

> But my question is that is there a way to compare 2

> list.

HAHAHAHAHAHAHAHAHAHAHAHAHAHA.

You may want to investigate what "intersection" means.

> someone posted a url for retainAll method

Hell, if you even bothered to read that link you'd see that it says

the intersection method is called retainAll()

TuringPesta at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 26
you must compare one by one index on lista to listb.check it one by one
mas_dadanga at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 27

HAHAHHAHAAHAHAHAHA I am laughing my butt out also. Very funny.

according to the url kevjava posted

retainAll

boolean retainAll(Collection<?> c)Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all the elements that are not contained in the specified collection.

Specified by:

retainAll in interface Collection<E>

Parameters:

c - collection that defines which elements this set will retain.

Returns:

true if this list changed as a result of the call.

Throws:

UnsupportedOperationException - if the retainAll method is not supported by this list.

ClassCastException - if the types of one or more elements in this list are incompatible with the specified collection (optional).

NullPointerException - if this list contains one or more null elements and the specified collection does not support null elements (optional).

NullPointerException - if the specified collection is null.

See Also:

remove(Object), contains(Object)

Am i missing something about intersection or am i blind to see if the intersection is printed?

lrngjavaa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 28
forget it i will just iterate through each index of list and then store it in a string like xpyro posted and then compare it. sounds resonable rather than converting it into set or map.
lrngjavaa at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 29

for each item in listA {

if listB contains current item {

print both lists contain current item

} else {

current item is in listA but not listB

}

}

This requires you to have provided an adequate equals method if your list contain objects of a class you wrote.

Message was edited by:

flounder

floundera at 2007-7-21 22:06:09 > top of Java-index,Java Essentials,New To Java...
# 30

> however, if you would like to do it another way, however in

> eficcient you could use a nested for loop.

Source from GNU classpath:

533boolean retainAllInternal(Collection c)

534{

535int i;

536int j;

537for (i = 0; i < size; i++)

538if (! c.contains(data[i]))

539 break;

540if (i == size)

541return false;

542

543modCount++;

544for (j = i++; i < size; i++)

545if (c.contains(data[i]))

546 data[j++] = data[i];

547size -= i - j;

548return true;

549}

(retrieved from http://www.docjar.com/html/api/java/util/ArrayList.java.html)

So, even if you iterate through the list yourself, you're going to be just about as efficient as calling retainAll(List), because the real implementation probably does something very similar.

kevjavaa at 2007-7-21 22:06:14 > top of Java-index,Java Essentials,New To Java...
# 31

public boolean hasDuplicateButSideEffect(List a, List b) {

a.retainAll(b);

return a.size() > 0;

}

yeah... simply iterate it and you can add a break when you found one duplicate.

j_shadinataa at 2007-7-21 22:06:14 > top of Java-index,Java Essentials,New To Java...
# 32

> HAHAHHAHAAHAHAHAHA I am laughing my butt out also.

> Very funny.

yea the world is a horrible place.

import java.util.*;

public class SetIntersection{

public static void main(String[] args){

new SetIntersection();

}

public SetIntersection(){

String[] bandList1 = {"sonic youth", "klaxons", "the knife", "clutch", "xiu xiu"};

String[] bandList2 = {"!!!", "arcade fire", "clutch", "xiu xiu"};

List bl1 = Arrays.asList(bandList1);

List bl2 = Arrays.asList(bandList2);

HashSet s1 = new HashSet(bl1);

HashSet s2 = new HashSet(bl2);

print(s1);

print(s2);

s1.retainAll(s2);

print(s1);

}

public void print(Collection c){

Iterator i = c.iterator();

System.out.println("\nCollection");

while(i.hasNext()){

System.out.println("Item: " + (String)i.next());

}

}

}

Collection

Item: sonic youth

Item: xiu xiu

Item: clutch

Item: the knife

Item: klaxons

Collection

Item: xiu xiu

Item: clutch

Item: !!!

Item: arcade fire

Collection

Item: xiu xiu

Item: clutch

TuringPesta at 2007-7-21 22:06:14 > top of Java-index,Java Essentials,New To Java...
# 33
a.retainAll(b) worked for me pretty good. i was defining the method wrong. got it.
lrngjavaa at 2007-7-21 22:06:14 > top of Java-index,Java Essentials,New To Java...
# 34
It works as long as you no longer need all the other values in the Collection.
floundera at 2007-7-21 22:06:14 > top of Java-index,Java Essentials,New To Java...
# 35
thanks flounder and shadinta. i am able to print the duplicates also which are in list.
lrngjavaa at 2007-7-21 22:06:14 > top of Java-index,Java Essentials,New To Java...
# 36
> It works as long as you no longer need all the other values in the Collection. HashSet.clone()it just does a shallow copy of the collection
TuringPesta at 2007-7-21 22:06:14 > top of Java-index,Java Essentials,New To Java...