集合练习题

【题目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;
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,905评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,140评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,791评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,483评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,476评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,516评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,905评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,560评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,778评论 1 296
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,557评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,635评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,338评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,925评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,898评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,142评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,818评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,347评论 2 342

推荐阅读更多精彩内容