String (@NotNull List<? extends HighlightInfo> highlightInfos, @NotNull CharSequence documentSequence, @Nullable Set<String> acceptableKeyNames) { List<Pair<Integer, String>> sortedMarkers = highlightInfos.stream() .flatMap(it -> { String keyText = it.type.getAttributesKey().toString(); if (acceptableKeyNames != null && !acceptableKeyNames.contains(keyText)) { return Stream.empty(); } return Stream.of( Pair.create(it.getStartOffset(), "<" + keyText + ">"), Pair.create(it.getEndOffset(), "</" + keyText + ">") ); }) .sorted(MARKERS_COMPARATOR).toList(); StringBuilder sb = new StringBuilder(); int lastEnd = 0; for (Pair<Integer, String> marker : sortedMarkers) { Integer startOffset = marker.first; if (startOffset > lastEnd) { sb.append(documentSequence.subSequence(lastEnd, startOffset)); lastEnd = startOffset; } sb.append(marker.second); } return sb.append(documentSequence.subSequence(lastEnd, documentSequence.length())).toString(); }