雪洗中关村

导航

java8 array、list操作 汇【3】)(-Java8新特性之 收集器Collectors 详解

 

 

复制代码
public class BaseTest {
    /* 转载:https://blog.csdn.net/u013291394/article/details/52662761
            git: https://github.com/shekhargulati/java8-the-missing-tutorial/tree/master/code
        */
    public static void main(String[] args) {
        BaseTest tt = new BaseTest();
//        tt.titleSummary(DataUtils.getTasks());
        tt.taskTest1();

    }

    public void taskTest1() {
        List<Task> tasks = DataUtils.getTasks();
        Map<TaskType, List<Task>> allTasksByType = new HashMap<>();
        for (Task task : tasks) {
            List<Task> existingTasksByType = allTasksByType.get(task.getType());
            if (existingTasksByType == null) {
                List<Task> tasksByType = new ArrayList<>();
                tasksByType.add(task);
                allTasksByType.put(task.getType(), tasksByType);
            } else {
                existingTasksByType.add(task);
            }
        }
        for (Map.Entry<TaskType, List<Task>> entry : allTasksByType.entrySet()) {
            System.out.println(String.format("%s =>> %s", entry.getKey(), entry.getValue()));
        }

        //生成统计信息
        IntSummaryStatistics summaryStatistics = tasks.stream().map(Task::getTitle).collect(summarizingInt(String::length));
        System.out.println(summaryStatistics.getAverage()); //32.4
        System.out.println(summaryStatistics.getCount()); //5
        System.out.println(summaryStatistics.getMax()); //44
        System.out.println(summaryStatistics.getMin()); //24
        System.out.println(summaryStatistics.getSum()); //162
    }


    //找到拥有最长标题的任务
    public Task taskWithLongestTitle(List<Task> tasks) {
////      Optional<Task> collect = tasks.stream().collect(Collectors.maxBy(Comparator.comparingInt(t -> t.getTitle().length())) );
//        Optional<Task> collect = tasks.stream().collect(maxBy(Comparator.comparingInt(t -> t.getTitle().length())));
////      Optional<Task> collect = tasks.stream().collect(maxBy((t1, t2) -> t1.getTitle().length() - t2.getTitle().length()));
//        Task task = collect.get();
//        return task;
        Task collect = tasks.stream().collect(collectingAndThen(maxBy((t1, t2) -> t1.getTitle().length() - t2.getTitle().length()), Optional::get));
        System.out.println(collect.getTitle());
        return collect;
    }

    //分割
    private static Map<Boolean, List<Task>> partitionOldAndFutureTasks(List<Task> tasks) {
        return tasks.stream().collect(partitioningBy(task -> task.getDueOn().isAfter(LocalDate.now())));
    }

    //统计标签的总数
    public int totalTagCount(List<Task> tasks) {
        Integer collect = tasks.stream().collect(summingInt(task -> task.getTags().size()));
        System.out.println("BaseTest.totalTagCount: "+collect);
        return collect;
    }

    //分类收集器
    //例子1:根据类型对任务分类
    private static Map<TaskType, List<Task>> groupTasksByType(List<Task> tasks) {
        return tasks.stream().collect(groupingBy(Task::getType));
    }




    //例子2:根据标签分类
    private static Map<String, List<Task>> groupingByTag(List<Task> tasks) {
        return tasks.stream().
                flatMap(task -> task.getTags().stream().map(tag -> new TaskTag(tag, task))).
                collect(groupingBy(TaskTag::getTag, mapping(TaskTag::getTask,toList())));
    }
    //例子3:根据标签和数量对任务分类
    private static Map<String, Long> tagsAndCount(List<Task> tasks) {
        return tasks.stream().
                flatMap(task -> task.getTags().stream().map(tag -> new TaskTag(tag, task))).
                collect(groupingBy(TaskTag::getTag, counting()));
    }

    //例子4:根据任务类型和创建日期分类
    private static Map<TaskType, Map<LocalDate, List<Task>>> groupTasksByTypeAndCreationDate(List<Task> tasks) {
        return tasks.stream().collect(groupingBy(Task::getType, groupingBy(Task::getCreatedOn)));
    }

    //简单-生成任务标题的概述
    public String titleSummary(List<Task> tasks) {
        return tasks.stream().map(Task::getTitle).collect(joining(";"));
    }







    //实体:
    public static enum TaskType {
        READING, CODING, BLOGGING
    }
    //bean
    public static class Task {

        private LocalDate dueOn;

        private final String id;
        private final String title;
        private final String description;
        private final TaskType type;
        private LocalDate createdOn;
        private Set<String> tags = new HashSet<>();

        public Task(final String id, final String title, final TaskType type) {
            this.id = id;
            this.title = title;
            this.description = title;
            this.type = type;
            this.createdOn = LocalDate.now();
        }

        public Task(final String title, final TaskType type) {
            this(title, title, type, LocalDate.now());
        }

        public Task(final String title, final TaskType type, final LocalDate createdOn) {
            this(title, title, type, createdOn);
        }

        public Task(final String title, final String description, final TaskType type, final LocalDate createdOn) {
            this.id = UUID.randomUUID().toString();
            this.title = title;
            this.description = description;
            this.type = type;
            this.createdOn = createdOn;
        }

        public LocalDate getDueOn() {
            return dueOn;
        }

        public void setDueOn(LocalDate dueOn) {
            this.dueOn = dueOn;
        }

        public String getId() {
            return id;
        }

        public String getTitle() {
            return title;
        }

        public String getDescription() {
            return description;
        }

        public TaskType getType() {
            return type;
        }

        public LocalDate getCreatedOn() {
            return createdOn;
        }

        public Task addTag(String tag) {
            this.tags.add(tag);
            return this;
        }

        public Set<String> getTags() {
            return Collections.unmodifiableSet(tags);
        }

        @Override
        public String toString() {
            return "Task{" +
                    "title='" + title + '\'' +
                    ", type=" + type +
                    '}';
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Task task = (Task) o;
            return Objects.equals(title, task.title) &&
                    Objects.equals(type, task.type);
        }

        @Override
        public int hashCode() {
            return Objects.hash(title, type);
        }
    }
    private static class TaskTag {
        final String tag;
        final Task task;

        public TaskTag(String tag, Task task) {
            this.tag = tag;
            this.task = task;
        }

        public String getTag() {
            return tag;
        }

        public Task getTask() {
            return task;
        }
    }

    public static class DataUtils {

        public static Stream<String> lines() {
            return filePathToStream("src/main/resources/book.txt");
        }

        public static Stream<String> negativeWords() {
            return filePathToStream("src/main/resources/negative-words.txt");
        }

        public static Stream<String> filePathToStream(String path) {
            try {
                return Files.lines(Paths.get("training", path));
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        public static IntStream range(int start, int end) {
            return IntStream.rangeClosed(start, end);
        }

        public static List<Task> getTasks() {
            Task task1 = new Task("Read Java 8 in action", TaskType.READING, LocalDate.of(2015, Month.SEPTEMBER, 20)).addTag("java").addTag("java8").addTag("books");
            Task task2 = new Task("Write factorial program in Haskell", TaskType.CODING, LocalDate.of(2015, Month.SEPTEMBER, 20)).addTag("program").addTag("haskell").addTag("functional");
            Task task3 = new Task("Read Effective Java", TaskType.READING, LocalDate.of(2015, Month.SEPTEMBER, 21)).addTag("java").addTag("books");
            Task task4 = new Task("Write a blog on Stream API", TaskType.BLOGGING, LocalDate.of(2015, Month.SEPTEMBER, 21)).addTag("writing").addTag("stream").addTag("java8");
            Task task5 = new Task("Write prime number program in Scala", TaskType.CODING, LocalDate.of(2015, Month.SEPTEMBER, 22)).addTag("scala").addTag("functional").addTag("program");
            return Stream.of(task1, task2, task3, task4, task5).collect(toList());
        }
    }

}
复制代码

 

posted on   雪洗中关村  阅读(349)  评论(0编辑  收藏  举报

努力加载评论中...
点击右上角即可分享
微信分享提示