String chars Builds Sort Signatures
Turn a string into an IntStream of chars, sort it, and compare signatures so anagram detection stays allocation-light on primitive streams.
Code
import java.util.List;
import java.util.stream.IntStream;
public class AnagramCheck {
// 变位词签名:字符排序后的规范形态。chars() 给 IntStream,
// sorted() 在基本类型流上排序,不装箱
static String signature(String word) {
IntStream chars = word.toLowerCase().chars();
StringBuilder sb = new StringBuilder();
chars.sorted().forEach(c -> sb.append((char) c));
return sb.toString();
}
public static void main(String[] args) {
System.out.println("listen -> " + signature("listen"));
System.out.println("silent -> " + signature("silent"));
List<String> words = List.of("listen", "silent", "enlist",
"google", "banana", "inlets");
String target = signature("silent");
List<String> anagrams = words.stream()
.filter(w -> signature(w).equals(target))
.toList();
System.out.println("anagrams of silent: " + anagrams);
// 大小写归一后 signature 一致:Listen 也是变位词
System.out.println("Listen is anagram: "
+ signature("Listen").equals(target));
}
}Step-by-step behavior
The moving parts are the class AnagramCheck and the functions signature and main.
The pipeline is a stream: source, lazy intermediate steps, one terminal collector.
What to watch for
- The toolchain by itself is enough — no dependency resolution step.
Using it
The signature that fronts the file: static String signature(String word)
Each step prints a labeled line — listen ->, silent ->, anagrams of silent: — when the file runs.
Execute the file and main walks through signature, in that order.
Lines that carry the behavior
return sb.toString();
.filter(w -> signature(w).equals(target))
.toList();
Interactive Tools for This Topic
Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does String chars Builds Sort Signatures print when run?
- Running the file directly is enough — expect labeled output lines such as `listen ->`, `silent ->`, `anagrams of silent:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.