raj <2rajesh.b@gmail.com> wrote in
news:f4142d9e-985f-4cbc-906a-f354d3ff32fc@v35g2000pro.googlegroups.com:
On Apr 14, 5:04?pm, Steven Simpson <s...@domain.invalid> wrote:
Lars Enderin wrote:
raj wrote:
? ? String s1 ="hello,test,from,one,party";
? ? String s2 = "into,bytes,hello,to";
i need to compare s1 values with s2 values if exists i need to
return the matched value.
hello in s1 is present in s2 ..i neeed to return hello...
You can use s1.split(",") and s2.split(",") to create two String
arrays. Then you compare the arrays element by element.
Or convert those arrays to Lists with Arrays.asList(T[]), make a
HashSet out of one of them, and pass the other to its
retainAll(Collection) metho
d.
--
ss at comp dot lancs dot ac dot uk
thanks alot
i tried out and got it
public class StringComp {
public static void main(String args[]) {
String s1 ="hello,test,from,cbn,party";
String s2 = "jain,dead,hello,to,cbn";
String sold [] = s1.split(",");
for(int i =0 ;i<sold.length;i++) {
String out = sold[i];
String snew [] = s2.split(",");
for(int j=0; j<snew.length; j++){
String in = snew[j];
if(in.equalsIgnoreCase(out)){
System.out.println("equal: " +in);
}
}
}
}
Done with the mentioned Arrays.asList() and retainAll()
package retainall;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
String s1 ="hello,test,from,cbn,party";
String s2 = "jain,dead,hello,to,cbn";
List<String> l1 = new ArrayList(Arrays.asList(s1.split(","))) ;
List<String> l2 = new ArrayList(Arrays.asList(s2.split(","))) ;
l1.retainAll(l2);
for (String s : l1)
{
System.out.println("equal: " + s) ;
}
}
}
The lists must be created as an ArrayList, as the asList() returned
Collections do not support remove().
Tuned up version. This does not use Lists and prints the values in sorted
order.