List去重复/判断List是否包含某元素/字符串是否包含
Java的几个最最最简单的日常应用:
public class TheProblemsWereNotAProblem {
?/**
? * 这种方法只适合用来比较一些字符串是否包含的问题
? * 比较传入String string中是否含有与传入的String str相同的部分,
? * @param list
? * @param str
? * @return
? */
?public static boolean isItIn(String string,String str) throws Exception {
??// 自左向右,不论字符串长度是否相同只要前面的字符完全匹配就返回TRUE;
??if (string.contains(str)) {// .contains JDK1.5之后才有
???return true;
??}
??return false;
?}
?
?/**
? * 这种方法适合用来比较List中是否包含某个元素的问题
? * 比较传入List list中是否含有与传入的String str相同的元素
? * @param list
? * @param str
? * @return
? * @throws Exception
? */
?public static boolean isItEquals(List list,String str) throws Exception {
??for (int i = 0; i < list.size(); i++) {
???if (str.equals(list.get(i).toString())) {
????return true;
???}
??}
??return false;
?}
?/**
? * 去除list中重复的元素
? * @param l
? * @return
? * @throws Exception
? */
?public static List removeRepeatElement(List l) throws Exception {
??Set set = new HashSet();
??List list = new ArrayList();
??System.out.println();
??System.out.println(l.size()+"传入的List的长度");
??for (int i = 0; i < l.size(); i++) {
???set.add(l.get(i));
??}
??System.out.println();
??System.out.println(set.size()+"处理后set的长度");
??System.out.println();
??for (Iterator it = set.iterator(); it.hasNext();) {
???list.add(it.next());
??}
??System.out.println(list.size()+"返回的list的长度");
??System.out.println();
??return list;
?}
?public static void main(String[] args) throws Exception {
??String[] s = new String[] {
???"BJ", "SH", "CQ", "TJ", "BJ", "SH", "CQ", "TJ"
??};
??List l = new ArrayList();
??for (int i = 0; i < s.length; i++) {
???l.add(s[i]);
??}
??List list=removeRepeatElement(l);//去重复
??for (int i = 0; i < list.size(); i++) {
???System.out.println(list.get(i).toString());
??}
??System.out.println();
??//System.out.println(list.toString());
??System.out.println(isItIn(list.toString(),"B"));// 返回ture
??System.out.println(isItIn(list.toString(),"BJ"));// 返回ture
??System.out.println(isItIn(list.toString(),"BJS"));// 返回false
??System.out.println();
??System.out.println(isItEquals(list,"B"));// 返回flase
??System.out.println(isItEquals(list,"BJ"));// 返回ture
??System.out.println(isItEquals(list,"BJS"));// 返回false
??
?}
}