第13周作业集

题目1:创建两个线性表,分别存储{“chen”,“wang”,“liu”,“zhang”}和{“chen”,“hu”,“zhang”},求这两个线性表的交集和并集。

package homework.thirteen;

import java.util.HashSet;
import java.util.Set;

public class One {
    public static void main(String[] args) {
        Set<String> one = new HashSet<>() {{
            add("chen");
            add("wang");
            add("liu");
            add("zhang");
        }};
        Set<String> two = new HashSet<>() {{
            add("chen");
            add("hu");
            add("zhang");
        }};
        Set<String> result = new HashSet<>(one);
        result.retainAll(two);
        System.out.println("交集:" + result);

        result.clear();
        result.addAll(one);
        result.addAll(two);
        System.out.println("并集:" + result);
    }
}

 

题目2:编写一个应用程序,输入一个字符串,该串至少由数字、大写字母和小写字母三种字符中的一种构成,如“123”、“a23”、“56aD”、“DLd”、“wq”、“SSS”、“4NA20”,对输入内容进行分析,统计每一种字符的个数,并将该个数和每种字符分别输出显示。如:输入内容为“34Ah5yWj”,则输出结果为:数字——共3个,分别为3,4,5;小写字母——共3个,分别为h,y,j;大写字母——共2个,分别为A,W。

 

package homework.thirteen;

import java.util.*;
import java.util.function.Function;

enum State {
    // 小写字母 , 大写字母, 数字
    Lowercase("小写字母", "[a-z]"),
    Uppercase("大写字母", "[A-Z]"),
    Integer("数字", "\\d"),
    ;
    private String name;
    private String regex;

    State(String name, String regex) {
        this.name = name;
        this.regex = regex;
    }

    public String getName() {
        return name;
    }

    public String getRegex() {
        return regex;
    }
}

public class Two {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        final String input = scanner.nextLine();
        if (!input.matches("\\w+")) {
            System.out.println("输入的字符串至少由数字、大写字母和小写字母三种字符中的一种构成!");
            return;
        }

        Map<String, String> result = new HashMap<>(State.values().length);

        Function<String, String> getNameByRegex = s -> Arrays.stream(State.values())
            .filter(e -> s.matches(e.getRegex())).findFirst().get().getName();

        Arrays.stream(input.split("")).forEach(e ->
            result.compute(getNameByRegex.apply(e), (k, v) -> v == null ? e : v + e));

        result.forEach((k, v) -> System.out.println(
            k + "——共" + v.length() + "个,分别为 " + String.join(" ,", v.split(""))));
    }
}

 

 

 

posted @ 2019-12-01 22:15  昵称是个啥~~  阅读(155)  评论(1编辑  收藏  举报