不错
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- /*
- 题目:已知集合List<String> listA = new ArrayList<String>();
- listA中有“1234”,“2456”,“3654”,“4765”,“5324”,“6098”,“7890”,“1091”,“2670”对象。
- 已知集合List<Integer> listB = new ArrayList<Integer>();
- listB中有1,2,3,4,5,6,7,1,2对象。
- 现在请:将listA中的对象拆分成单独的数字字符串(
- 也就是将“1234”,拆分成“1”,“2”,“3”,“4”四个对象),
- 并保存在集合listA中①给listA、listB分别去重
- ②创建新集合List<String> listC = new ArrayList<String>();
- 将listA和listB中相同(字符相同则相同)的对象保存到listC
- ③给集合listC按照数字倒序排列,然后输出。
- 上传代码的时候将运算结果截图一起提交。
- * */
- public class ListOperation {
- public static void print(Object obj)
- {
- System.out.println(obj);
- }
- public static void main(String[]args)
- {
- List<String> al1 = new ArrayList<String>();
- List<Integer> al2 = new ArrayList<Integer>();
- List<String> al3 = new ArrayList<String>();
- strGenerator(al1);
- intGenerator(al2);
- print("原listA集合:"+al1);
- converseFunc(al1);
- print("修改后的listA集合:"+al1);
- removeDoubleFunc(al1);
- print("去重复后的listA集合:"+al1);
- removeDoubleFunc(al2);
- print("去重复后的listB集合:"+al2);
- al3=retainDoubleFunc(al1,al2);
- print("listC集合:"+al3);
- Collections.reverse(al3);
- print("修改后的listC集合:"+al3);
- }
- public static void strGenerator(List<String> list)
- {
- Collections.addAll(list,"1234","2456","3654","4765","5324","6098","7890","1091","2670");
- }
- public static void intGenerator(List<Integer>list)
- {
- Collections.addAll(list, 1,2,3,4,5,6,7,1,2);
- }
- public static void converseFunc(List<String>list)
- {
- list.clear();
- List<String> list1 = new ArrayList<String>();
- strGenerator(list1);
- for(String s:list1)
- {
- char[]arr=s.toCharArray();
- for(char c:arr)
- list.add(Character.toString(c));
- }
- }
- public static <T>void removeDoubleFunc(List<T>list)
- {
- ArrayList<T>al=new ArrayList<T>();
- for(T s:list)
- {
- if(!al.contains(s))
- al.add(s);
- }
- list.clear();
- list.addAll(al);
- }
- public static List<String> retainDoubleFunc(List<String> list1,List<Integer>list2)
- {
- ArrayList<String> al=new ArrayList<String>();
- for(int x:list2)
- {
- al.add(Integer.toString(x));
- }
- al.retainAll(list1);
- return al;
- }
- }
复制代码 |