代码如下:
package com.hp.test;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
/**
* 提取多个字符串相同的字符
* @author HP
*
*/
public class StringTest{
/**
* 提取相同字符
* abc a b c
* bcd b c d
* cde c d e
* @param list
* @return
*/
public static LinkedHashSet<Character> getCommonChar(List<String> list){
//创建结果集合
LinkedHashSet<Character> resultList = new LinkedHashSet<>();
//对数据进行处理
if(list != null && list.size()>0){//集合不为空
//创建集合
LinkedHashSet<Character> charList = new LinkedHashSet<>();
for (String string : list) {//循环集合
char[] charArray = string.toCharArray();
for (char c : charArray) {
charList.add(c);
}
}
//对全部字符去重,去重结果即为公共元素
resultList.addAll(charList);
System.out.println(charList);
LinkedHashSet<Character> temp = new LinkedHashSet<>();//中间集合
LinkedHashSet<Character> other = new LinkedHashSet<>();//不是公共字符的集合
for (String string : list) {
char[] charArray = string.toCharArray();
//移除
for (char c : charArray) {
charList.remove(c);
}
//中间交互值
temp.addAll(charList);//得到去除后的集合
other.addAll(temp);//添加到不是公共字符里
System.out.println(temp+"--------------");
charList.addAll(resultList);
System.out.println(charList+"*********");
temp.clear();//清空中间集合
System.out.println("--------------------------------");
}
// 去除不是公共的字符
resultList.removeAll(other);
}
System.out.println("结果为:"+resultList);
//返回公共字符
return resultList;
}
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("abc");
list.add("bcd");
list.add("cde");
getCommonChar(list);
}
}
执行结果如下:
[a, b, c, d, e]
[d, e]--------------
[d, e, a, b, c]*********
--------------------------------
[e, a]--------------
[e, a, b, c, d]*********
--------------------------------
[a, b]--------------
[a, b, c, d, e]*********
--------------------------------
结果为:[c]
分析:
1.当传入多个字符串时就不能简单的像俩个字符串提取一样,必须要转换思路,也就是先把所有的字符保存到一个总的集合里面,
2.对字符串集合遍历,对每个字符串进行去重操作,之所以进行去重,是因为如果一个字符串都不包含这个字符,那么这个字符一定不是公共字符,
3.用总的字符集合,减去不是公共字符的总集合,得到公共字符总集合.