美文网首页
集合练习题

集合练习题

作者: 上杉丶零 | 来源:发表于2019-08-04 03:32 被阅读0次

    【题目1】一个ArrayList对象中有若干个字符串元素,现在遍历该ArrayList对象,删除其中所有值为abc的字符串元素。

    • 思路:
      1. 创建类型为String的List集合
      2. 添加元素
      3. 遍历集合
      4. 删除元素
    • 注意:正着遍历时,当集合中有连续的abc存在时,会出现删除不干净的情况,需在每次删除后角标自动减一位,或者可以选择倒着遍历。
    package leif;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test {
        public static void main(String[] args) {
            List<String> sList = new ArrayList<String>() {
                private static final long serialVersionUID = 1L;
    
                {
                    add("abc");
                    add("a");
                    add("abc");
                    add("b");
                    add("abc");
                    add("abc");
                    add("c");
                    add("abc");
                    add("d");
                    add("abc");
                }
            };
    
            System.out.println(sList);
    
            for (int i = 0; i < sList.size(); i++) {
                if ("abc".equals(sList.get(i))) {
                    sList.remove(i);
                    i--;
                }
            }
    
            System.out.println(sList);
        }
    }
    

    Java8

    package leif;
    
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Test {
        public static void main(String[] args) {
            List<String> sList = Stream.of("abc", "a", "abc", "b", "abc", "abc", "c", "abc", "d", "abc").collect(Collectors.toList());
            sList.stream().forEach(System.out::println);
            sList.stream().filter(s -> !s.equals("abc")).forEach(System.out::println);
        }
    }
    

    【题目2】取出一个字符串中字母出现的次数,如:"abcdekka27qoq"输出格式为a(2)b(1)k(2)。

    • 思路:
      1. 创建Key类型为Character、Value类型为Integer的Map集合
      2. 遍历字符串
      3. 判断集合中是否有Key值为当前字符的元素
      4. 若无,则将当前字符作为Key值存入集合,并将Value值设为1;若有,则取出Key值为当前字符的元素,并将Value值增加1
      5. 遍历集合,以规定格式输出各元素
    package leif;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    
    public class Test {
        public static void main(String[] args) {
            String s = "abcdekka27qoq";
            Map<Character, Integer> cMap = new HashMap<>();
    
            for (char c : s.toCharArray()) {
                if (cMap.containsKey(c)) {
                    cMap.put(c, cMap.get(c) + 1);
                } else {
                    cMap.put(c, +1);
                }
            }
    
            StringBuffer stringBuffer = new StringBuffer();
    
            for (Entry<Character, Integer> cEntry : cMap.entrySet()) {
                stringBuffer.append(cEntry.getKey() + "(" + cEntry.getValue() + ")");
            }
    
            System.out.println(stringBuffer);
        }
    }
    

    Java8

    package leif;
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Test {
        public static void main(String[] args) {
            String s = "abcdekka27qoq";
    
            Map<String, Integer> sMap = new HashMap<String, Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    put("index", -1);
                }
            };
    
            Stream.generate(() -> {
                int index = sMap.get("index") + 1;
                sMap.put("index", index);
                return s.substring(index, index + 1);
            }).limit(s.length()).collect(Collectors.groupingBy(letter -> letter, Collectors.counting())).entrySet().stream().forEach(letterEntry -> System.out.print(letterEntry.getKey() + "(" + letterEntry.getValue() + ")"));
        }
    }
    

    【题目3】编写程序,随机生成5个1~10之间的随机数,存入一个List集合中,编写方法对List集合进行降序排列。

    • 思路:
      1. 创建类型为Integer的List集合
      2. 生成5个1-10之间的随机数,并存入集合中
      3. 排序
    • 注意:random.nextInt(10)产生的随机数区间为[0, 10)。
    package leif;
    
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Random;
    
    public class Test {
        public static void main(String[] args) {
            Random random = new Random();
    
            List<Integer> iList = new ArrayList<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    for (int i = 0; i < 5; i++) {
                        add(random.nextInt(10) + 1);
                    }
                }
            };
    
            System.out.println(iList);
    
            iList.sort(new Comparator<Integer>() {
                @Override
                public int compare(Integer i1, Integer i2) {
                    return i2 - i1;
                }
            });
    
            System.out.println(iList);
        }
    }
    

    Java8

    package leif;
    
    import java.util.List;
    import java.util.Random;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Test {
        public static void main(String[] args) {
            Random random = new Random();
    
            List<Integer> iList = Stream.generate(() -> random.nextInt(10) + 1).limit(5).collect(Collectors.toList());
            System.out.println(iList);
            iList.stream().sorted((i1, i2) -> i2 - i1).forEach(System.out::println);
        }
    }
    

    【题目4】创建俩个散列规则集,求它们的并集、差集和交集。

    package leif;
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class Test {
        public static void main(String[] args) {
            Set<Integer> iSet1 = new HashSet<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    add(1);
                    add(2);
                    add(3);
                    add(4);
                    add(5);
                }
            };
    
            System.out.println(iSet1);
    
            Set<Integer> iSet2 = new HashSet<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    add(3);
                    add(4);
                    add(5);
                    add(6);
                    add(7);
                }
            };
    
            System.out.println(iSet2);
    
            Set<Integer> unionSet = new HashSet<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    addAll(iSet1);
                    addAll(iSet2);
                }
            };
    
            System.out.println(unionSet);
    
            Set<Integer> differenceSet = new HashSet<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    addAll(iSet1);
                    addAll(iSet2);
                    removeAll(iSet2);
                }
            };
    
            System.out.println(differenceSet);
    
            Set<Integer> intersectionSet = new HashSet<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    addAll(iSet1);
                    retainAll(iSet2);
                }
            };
    
            System.out.println(intersectionSet);
        }
    }
    

    Java8

    package leif;
    
    import java.util.Set;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Test {
        public static void main(String[] args) {
            Set<Integer> iSet1 = Stream.of(1, 2, 3, 4, 5).collect(Collectors.toSet());
            System.out.println(iSet1);
            Set<Integer> iSet2 = Stream.of(3, 4, 5, 6, 7).collect(Collectors.toSet());
            System.out.println(iSet2);
            Set<Integer> unionSet = Stream.of(iSet1, iSet2).flatMap(iSet -> iSet.stream()).collect(Collectors.toSet());
            System.out.println(unionSet);
            Set<Integer> differenceSet = iSet1.stream().filter(i -> !iSet2.contains(i)).collect(Collectors.toSet());
            System.out.println(differenceSet);
            Set<Integer> intersectionSet = iSet1.stream().filter(i -> iSet2.contains(i)).collect(Collectors.toSet());
            System.out.println(intersectionSet);
        }
    }
    

    【题目5】创建俩个数组线性表,求它们的并集,差集和交集。

    package leif;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test {
        public static void main(String[] args) {
            List<Integer> iList1 = new ArrayList<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    add(1);
                    add(2);
                    add(3);
                    add(4);
                    add(5);
                }
            };
    
            System.out.println(iList1);
    
            List<Integer> iList2 = new ArrayList<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    add(3);
                    add(4);
                    add(5);
                    add(6);
                    add(7);
                }
            };
    
            System.out.println(iList2);
    
            List<Integer> unionList = new ArrayList<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    addAll(iList1);
    
                    for (int i : iList2) {
                        if (!contains(i)) {
                            add(i);
                        }
                    }
                }
            };
    
            System.out.println(unionList);
    
            List<Integer> differenceList = new ArrayList<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    addAll(iList1);
                    addAll(iList2);
                    removeAll(iList2);
                }
            };
    
            System.out.println(differenceList);
    
            List<Integer> intersectionList = new ArrayList<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    addAll(iList1);
                    retainAll(iList2);
                }
            };
    
            System.out.println(intersectionList);
        }
    }
    

    Java8

    package leif;
    
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Test {
        public static void main(String[] args) {
            List<Integer> iList1 = Stream.of(1, 2, 3, 4, 5).collect(Collectors.toList());
            System.out.println(iList1);
            List<Integer> iList2 = Stream.of(3, 4, 5, 6, 7).collect(Collectors.toList());
            System.out.println(iList2);
            List<Integer> unionList = Stream.of(iList1, iList2.stream().filter(i -> !iList1.contains(i)).collect(Collectors.toList())).flatMap(iList -> iList.stream()).collect(Collectors.toList());
            System.out.println(unionList);
            List<Integer> differenceList = iList1.stream().filter(i -> !iList2.contains(i)).collect(Collectors.toList());
            System.out.println(differenceList);
            List<Integer> intersectionList = iList1.stream().filter(i -> iList2.contains(i)).collect(Collectors.toList());
            System.out.println(intersectionList);
        }
    }
    

    【题目6】从文本中读取单词,将所有不重复的单词按升序显示。

    package leif;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Set;
    import java.util.TreeSet;
    
    public class Test {
        public static void main(String[] args) {
            StringBuilder stringBuilder = new StringBuilder();
    
            try (
                FileReader fileReader = new FileReader(new File("C:\\Users\\Administrator\\Desktop\\test.txt"));
                BufferedReader bufferedReader = new BufferedReader(fileReader);
            ) {
                String line = "";
    
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                    stringBuilder.append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            Set<String> sSet = new TreeSet<String>() {
                private static final long serialVersionUID = 1L;
    
                {
                    for (String s : stringBuilder.toString().split("\\W")) {
                        if (!"".equals(s)) {
                            add(s);
                        }
                    }
                }
            };
    
            System.out.println(sSet);
        }
    }
    

    Java8

    package leif;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Test {
        public static void main(String[] args) {
            StringBuilder stringBuilder = new StringBuilder();
    
            try (
                FileReader fileReader = new FileReader(new File("C:\\Users\\Administrator\\Desktop\\test.txt"));
                BufferedReader bufferedReader = new BufferedReader(fileReader);
            ) {
                String line = "";
    
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                    stringBuilder.append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            Stream.of(stringBuilder.toString().split("\\W")).filter(s -> !"".equals(s)).collect(Collectors.toSet()).stream().sorted().forEach(s -> System.out.print(s + " "));
        }
    }
    

    【题目7】从文本中读取单词,将所有单词按升序显示。

    package leif;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class Test {
        public static void main(String[] args) {
            StringBuilder stringBuilder = new StringBuilder();
    
            try (
                FileReader fileReader = new FileReader(new File("C:\\Users\\Administrator\\Desktop\\test.txt"));
                BufferedReader bufferedReader = new BufferedReader(fileReader);
            ) {
                String line = "";
    
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                    stringBuilder.append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            List<String> sList = new ArrayList<String>() {
                private static final long serialVersionUID = 1L;
    
                {
                    for (String s : stringBuilder.toString().split("\\W")) {
                        if (!"".equals(s)) {
                            add(s);
                        }
                    }
                }
            };
    
            Collections.sort(sList);
            System.out.println(sList);
        }
    }
    

    Java8

    package leif;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Test {
        public static void main(String[] args) {
            StringBuilder stringBuilder = new StringBuilder();
    
            try (
                FileReader fileReader = new FileReader(new File("C:\\Users\\Administrator\\Desktop\\test.txt"));
                BufferedReader bufferedReader = new BufferedReader(fileReader);
            ) {
                String line = "";
    
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                    stringBuilder.append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            Stream.of(stringBuilder.toString().split("\\W")).filter(s -> !"".equals(s)).collect(Collectors.toList()).stream().sorted().forEach(s -> System.out.print(s + " "));
        }
    }
    

    【题目8】读取一个java源文件,报告关键字的个数。

    package leif;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.HashMap;
    import java.util.Map;
    
    public class Test {
        private static final String KEYWORDS = "const, goto, public, protected, private, class, interface, abstract, implements, extends, new, import, package, byte, short, int, long, float, double, char, boolean, void, null, true, false, if, else, while, for, switch, case, default, do, break, continue, return, instanceof, static, final, super, this, native, strictfp, synchronized, transient, volatile, try, catch, finally, throw, throws, enum, assert";
    
        public static void main(String[] args) {
            Map<String, Integer> sIMap = new HashMap<String, Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    for (String s : KEYWORDS.split(", ")) {
                        put(s, 0);
                    }
                }
            };
    
            System.out.println(sIMap);
            StringBuilder stringBuilder = new StringBuilder();
    
            try (
                FileReader fileReader = new FileReader(new File("C:\\Users\\Administrator\\Desktop\\test.txt"));
                BufferedReader bufferedReader = new BufferedReader(fileReader);
            ) {
                String line = "";
    
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                    stringBuilder.append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            for (String s : stringBuilder.toString().split("\\W")) {
                if (sIMap.containsKey(s)) {
                    sIMap.put(s, sIMap.get(s) + 1);
                }
            }
    
            System.out.println(sIMap);
        }
    }
    

    Java8

    package leif;
    
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Map;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Test {
        private static final String KEYWORDS = "const, goto, public, protected, private, class, interface, abstract, implements, extends, new, import, package, byte, short, int, long, float, double, char, boolean, void, null, true, false, if, else, while, for, switch, case, default, do, break, continue, return, instanceof, static, final, super, this, native, strictfp, synchronized, transient, volatile, try, catch, finally, throw, throws, enum, assert";
    
        public static void main(String[] args) {
            Map<String, Integer> sIMap = Stream.of(KEYWORDS.split(", ")).collect(Collectors.toMap(keyword -> keyword, keyword -> 0));
            System.out.println(sIMap);
    
            StringBuilder stringBuilder = new StringBuilder();
    
            try (
                FileReader fileReader = new FileReader(new File("C:\\Users\\Administrator\\Desktop\\test.txt"));
                BufferedReader bufferedReader = new BufferedReader(fileReader);
            ) {
                String line = "";
    
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                    stringBuilder.append("\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            Stream.of(stringBuilder.toString().split("\\W")).forEach(s -> {
                if (sIMap.containsKey(s)) {
                    sIMap.put(s, sIMap.get(s) + 1);
                }
            });
    
            System.out.println(sIMap);
        }
    }
    

    【题目9】随机生成个数不定个整数,打印频率最高的,如果有俩个一样的最高频率则都输出。

    package leif;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Map.Entry;
    
    public class Test {
        public static void main(String[] args) {
            Map<Integer, Integer> iIMap = new HashMap<Integer, Integer>();
            int maxValue = 0;
    
            List<Integer> iList = new ArrayList<Integer>() {
                private static final long serialVersionUID = 1L;
    
                {
                    int number = (int) (Math.random() * 100 + 1);
    
                    for (int i = 0; i < number; i++) {
                        add((int) (Math.random() * 100 + 1));
                    }
                }
            };
    
            System.out.println(iList);
    
            for (int i : iList) {
                if (iIMap.containsKey(i)) {
                    iIMap.put(i, iIMap.get(i) + 1);
                } else {
                    iIMap.put(i, 1);
                }
    
                maxValue = Math.max(maxValue, iIMap.get(i));
            }
    
            for (Entry<Integer, Integer> iIEntry : iIMap.entrySet()) {
                if (iIEntry.getValue() == maxValue) {
                    System.out.println(iIEntry.getKey());
                }
            }
        }
    }
    

    Java8

    package leif;
    
    import java.util.List;
    import java.util.Map.Entry;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class Test {
        public static void main(String[] args) {
            List<Integer> iList = Stream.generate(() -> (int) (Math.random() * 100 + 1)).limit((long) (Math.random() * 100 + 1)).collect(Collectors.toList());
            System.out.println(iList);
            List<Entry<Integer, Long>> iEntryList = iList.stream().collect(Collectors.groupingBy(i -> i, Collectors.counting())).entrySet().stream().sorted(Entry.<Integer, Long>comparingByValue().reversed()).collect(Collectors.toList());
            iList = iEntryList.stream().filter(iLEntry -> iLEntry.getValue() == iEntryList.get(0).getValue()).map(iLEntry -> iLEntry.getKey()).collect(Collectors.toList());
            System.out.println(iList);
        }
    }
    

    【题目10】定义一个Point类,包含两个成员变量x和y,分别表示横坐标和纵坐标,随机创建100个点,升序显示这些点。

    package leif;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Random;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    public class Test {
        public static void main(String[] args) {
            Random random = new Random();
    
            List<Point> pointList = new ArrayList<Point>() {
                private static final long serialVersionUID = 1L;
    
                {
                    for (int i = 1; i <= 100; i++) {
                        add(new Point(random.nextInt(100), random.nextInt(100)));
                    }
                }
            };
    
            System.out.println(pointList);
    
            Collections.sort(pointList, new Comparator<Point>() {
                @Override
                public int compare(Point point1, Point point2) {
                    int i = point1.getX() - point2.getX();
    
                    if (i == 0) {
                        return point1.getY() - point2.getY();
                    } else {
                        return i;
                    }
                }
            });
    
            System.out.println(pointList);
        }
    }
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    class Point {
        private int x;
        private int y;
    }
    

    Java8

    package leif;
    
    import java.util.List;
    import java.util.Random;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;
    
    public class Test {
        public static void main(String[] args) {
            Random random = new Random();
            List<Point> pointList = Stream.generate(() -> new Point(random.nextInt(100), random.nextInt(100))).limit(100).collect(Collectors.toList());
            System.out.println(pointList);
            pointList = pointList.stream().sorted((Point point1, Point point2) -> point1.getX() - point2.getX() == 0 ? point1.getY() - point2.getY() : point1.getX() - point2.getX()).collect(Collectors.toList());
            System.out.println(pointList);
        }
    }
    
    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    class Point {
        private int x;
        private int y;
    }
    

    相关文章

      网友评论

          本文标题:集合练习题

          本文链接:https://www.haomeiwen.com/subject/adrvlctx.html