Skip to content

Instantly share code, notes, and snippets.

@asvignesh
Last active August 29, 2015 14:21
Show Gist options
  • Save asvignesh/56654ec2130b5271f97a to your computer and use it in GitHub Desktop.
Save asvignesh/56654ec2130b5271f97a to your computer and use it in GitHub Desktop.
Java List Contains for Custom Object Type
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by Vignesh on 26-05-2015.
*/
public class ContainsTest {
public static void main(String[] args) {
List<Integer> srcIntegerList = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
int destInt = 4;
if (srcIntegerList.contains(destInt)) {
System.out.println("Available");
} else {
System.out.println("Not Available");
}
List<String> srcStringList = new ArrayList<String>(Arrays.asList("vignesh", "A", "Sathiyanantham"));
String destString = "vignesh";
if (srcStringList.contains(destString)) {
System.out.println("Available");
} else {
System.out.println("Not Available");
}
MyClass myClass = new MyClass("Vignesh", 1);
MyClass myClass1 = new MyClass("asvignesh", 2);
List<MyClass> srcMyClassList = new ArrayList<MyClass>(Arrays.asList(myClass, myClass1));
MyClass destMyClass = new MyClass("asvignesh", 2);
if (srcMyClassList.contains(destMyClass)) {
System.out.println("Available");
} else {
System.out.println("Not Available");
}
}
}
/**
* Created by Vignesh on 26-05-2015.
*/
public class MyClass {
private int id;
private String name;
public MyClass(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public boolean equals(Object myObj) {
boolean isEquals = false;
if (myObj != null && myObj instanceof MyClass) {
isEquals = this.name.equals(((MyClass) myObj).name);
}
return isEquals;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment