Vou por um código passo a passo de uma solução trivial, ok?
Supondo que sua Collection esteja referenciada pela variável “coll”
public boolean existsName(String name) {
Iterator it = coll.iterator();
while(it.hasNext()){
Object elem = it.next();
if(elem instanceof JLabel) {
JLabel lbl = (JLabel)elem;
if(lbl.getText().equals(name))
return true;
}
}
return false;
}
(Editado…)
Uma solução um pouco mais sofisticada, seria vc criar uma TreeSet apartir dessa Collection e a partir de uma classe que implemente um Comparator:
public class Teste{
private Collection coll = Arrays.asList(
new JLabel[] {new JLabel("Mantuaneli"),
new JLabel("Luciano")}
);
public boolean existsName(JLabel lbl) {
TreeSet treeSet = new TreeSet(JLabelTextComparator.getInstance());
treeSet.addAll(coll);
return treeSet.contains(lbl);
}
public static class JLabelTextComparator implements Comparator{
private static JLabelTextComparator instance = null;
private JLabelTextComparator() {
}
public static JLabelTextComparator getInstance() {
if(instance == null)
instance = new JLabelTextComparator();
return instance;
}
public int compare(Object o1, Object o2) {
JLabel
lbl1 = (JLabel)o1,
lbl2 = (JLabel)o2
;
if(lbl1 == null || lbl2 == null)
throw new ClassCastException();
if(lbl1 == lbl2)
return 0;
String
text1 = lbl1.getText(),
text2 = lbl2.getText()
;
return text1.compareTo(text2);
}
}
public static void main(String[] args) {
Teste app = new Teste();
JLabel
label1 = new JLabel("Antonio"),
label2 = new JLabel("Luciano"),
label3 = new JLabel("Mantuaneli"),
label4 = new JLabel("Tertulino")
;
System.out.println("app.existsName(label1): " + app.existsName(label1));
System.out.println("app.existsName(label2): " + app.existsName(label2));
System.out.println("app.existsName(label3): " + app.existsName(label3));
System.out.println("app.existsName(label4): " + app.existsName(label4));
}
}