Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.company.parsing;
- import java.io.File;
- import java.io.IOException;
- import java.nio.charset.StandardCharsets;
- import java.nio.file.Files;
- import java.util.*;
- import java.util.stream.Collectors;
- import java.util.stream.IntStream;
- public class RecursiveParsing {
- public static final Map<Integer, Integer> map = new HashMap<>();
- public static final Set<Integer> keySet = new HashSet<>();
- public static String temp = "";
- public static final String TEXT = "# Sport\n" +
- "common text \n" +
- "## Tennis \n" +
- "### Table\n" +
- "### Ping Pong \n" +
- "commontext \n" +
- "# Dance";
- public static void main(String[] args) throws IOException {
- List<String> lines = Arrays.stream(TEXT.split("\n")).collect(Collectors.toList());
- StringBuilder header = new StringBuilder();
- StringBuilder body = new StringBuilder();
- lines.stream().filter(s -> s.startsWith("#")).forEach(s -> header.append(getValue(s)));
- map.clear();
- keySet.clear();
- lines.forEach(s -> body.append(getValue(s)));
- System.out.println(header);
- System.out.println(body);
- Scanner sc = new Scanner(System.in);
- }
- private static String diff(String s) {
- OptionalInt first = IntStream.range(0, s.length()).filter(i -> s.charAt(i) != ' ').findFirst();
- if (first.isPresent()) {
- return " ".repeat(Math.max(0, first.getAsInt()) - 1);
- }
- throw new NullPointerException();
- }
- public static String getValue(String sharp) {
- if (sharp.startsWith("#")) {
- temp = sharp.replace("#", " ");
- return merge(sharp, 0);
- } else {
- return "\n" + diff(temp) + sharp;
- }
- }
- private static String merge(String sharp, int section) {
- if (sharp.startsWith("#")) {
- return merge(sharp.substring(1), section + 1);
- } else {
- setupKeySet(section);
- return "\n" + " ".repeat(Math.max(0, section) - 1) + sharp + " " + getIndex(section);
- }
- }
- private static String getIndex(int section) {
- String value = "";
- if (section > 1) {
- value = getIndex(section - 1) + ".";
- }
- return value + Optional.ofNullable(map.get(section))
- .orElseThrow(() -> new UnsupportedOperationException("Нарушена вложенность разделов"));
- }
- private static void setupKeySet(int section) {
- map.merge(section, 1, Integer::sum);
- if (keySet.contains(section)) {
- keySet.forEach(key -> {
- if (key > section) map.remove(key);
- });
- } else {
- keySet.add(section);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement