Advertisement
Guest User

Untitled

a guest
Jun 4th, 2022
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.80 KB | None | 0 0
  1. package com.company.parsing;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.nio.charset.StandardCharsets;
  6. import java.nio.file.Files;
  7. import java.util.*;
  8. import java.util.stream.Collectors;
  9. import java.util.stream.IntStream;
  10.  
  11. public class RecursiveParsing {
  12.  
  13. public static final Map<Integer, Integer> map = new HashMap<>();
  14. public static final Set<Integer> keySet = new HashSet<>();
  15. public static String temp = "";
  16. public static final String TEXT = "# Sport\n" +
  17. "common text \n" +
  18. "## Tennis \n" +
  19. "### Table\n" +
  20. "### Ping Pong \n" +
  21. "commontext \n" +
  22. "# Dance";
  23.  
  24. public static void main(String[] args) throws IOException {
  25. List<String> lines = Arrays.stream(TEXT.split("\n")).collect(Collectors.toList());
  26. StringBuilder header = new StringBuilder();
  27. StringBuilder body = new StringBuilder();
  28. lines.stream().filter(s -> s.startsWith("#")).forEach(s -> header.append(getValue(s)));
  29. map.clear();
  30. keySet.clear();
  31. lines.forEach(s -> body.append(getValue(s)));
  32. System.out.println(header);
  33. System.out.println(body);
  34. Scanner sc = new Scanner(System.in);
  35. }
  36.  
  37. private static String diff(String s) {
  38. OptionalInt first = IntStream.range(0, s.length()).filter(i -> s.charAt(i) != ' ').findFirst();
  39. if (first.isPresent()) {
  40. return " ".repeat(Math.max(0, first.getAsInt()) - 1);
  41. }
  42. throw new NullPointerException();
  43. }
  44.  
  45. public static String getValue(String sharp) {
  46. if (sharp.startsWith("#")) {
  47. temp = sharp.replace("#", " ");
  48. return merge(sharp, 0);
  49. } else {
  50. return "\n" + diff(temp) + sharp;
  51. }
  52. }
  53.  
  54. private static String merge(String sharp, int section) {
  55. if (sharp.startsWith("#")) {
  56. return merge(sharp.substring(1), section + 1);
  57. } else {
  58. setupKeySet(section);
  59. return "\n" + " ".repeat(Math.max(0, section) - 1) + sharp + " " + getIndex(section);
  60. }
  61. }
  62.  
  63. private static String getIndex(int section) {
  64. String value = "";
  65. if (section > 1) {
  66. value = getIndex(section - 1) + ".";
  67. }
  68. return value + Optional.ofNullable(map.get(section))
  69. .orElseThrow(() -> new UnsupportedOperationException("Нарушена вложенность разделов"));
  70. }
  71.  
  72. private static void setupKeySet(int section) {
  73. map.merge(section, 1, Integer::sum);
  74. if (keySet.contains(section)) {
  75. keySet.forEach(key -> {
  76. if (key > section) map.remove(key);
  77. });
  78. } else {
  79. keySet.add(section);
  80. }
  81. }
  82. }
  83.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement