BAEL-3200 Error handling with Spring AMQP

This commit is contained in:
Alexander Molochko
2019-10-17 03:01:56 +03:00
parent db85c8f275
commit 70d5e7c57d
20386 changed files with 1639315 additions and 0 deletions
@@ -0,0 +1,21 @@
package com.baeldung.localization;
import java.text.ParseException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class App {
/**
* Runs all available formatter
* @throws ParseException
*/
public static void main(String[] args) {
List<Locale> locales = Arrays.asList(new Locale[] { Locale.UK, Locale.ITALY, Locale.FRANCE, Locale.forLanguageTag("pl-PL") });
Localization.run(locales);
JavaSEFormat.run(locales);
ICUFormat.run(locales);
}
}
@@ -0,0 +1,29 @@
package com.baeldung.localization;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
import com.ibm.icu.text.MessageFormat;
public class ICUFormat {
public static String getLabel(Locale locale, Object[] data) {
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
String format = bundle.getString("label-icu");
MessageFormat formatter = new MessageFormat(format, locale);
return formatter.format(data);
}
public static void run(List<Locale> locales) {
System.out.println("ICU formatter");
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 0 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 1 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 2 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Alice", "female", 3 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 0 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 1 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 2 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { "Bob", "male", 3 })));
}
}
@@ -0,0 +1,24 @@
package com.baeldung.localization;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class JavaSEFormat {
public static String getLabel(Locale locale, Object[] data) {
ResourceBundle bundle = ResourceBundle.getBundle("formats", locale);
final String pattern = bundle.getString("label");
final MessageFormat formatter = new MessageFormat(pattern, locale);
return formatter.format(data);
}
public static void run(List<Locale> locales) {
System.out.println("Java formatter");
final Date date = new Date(System.currentTimeMillis());
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 0 })));
locales.forEach(locale -> System.out.println(getLabel(locale, new Object[] { date, "Alice", 2 })));
}
}
@@ -0,0 +1,18 @@
package com.baeldung.localization;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;
public class Localization {
public static String getLabel(Locale locale) {
final ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
return bundle.getString("label");
}
public static void run(List<Locale> locales) {
locales.forEach(locale -> System.out.println(getLabel(locale)));
}
}
@@ -0,0 +1,83 @@
package com.baeldung.string;
import org.ahocorasick.trie.Emit;
import org.ahocorasick.trie.Token;
import org.ahocorasick.trie.Trie;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MatchWords {
public static boolean containsWordsIndexOf(String inputString, String[] words) {
boolean found = true;
for (String word : words) {
if (inputString.indexOf(word) == -1) {
found = false;
break;
}
}
return found;
}
public static boolean containsWords(String inputString, String[] items) {
boolean found = true;
for (String item : items) {
if (!inputString.contains(item)) {
found = false;
break;
}
}
return found;
}
public static boolean containsWordsAhoCorasick(String inputString, String[] words) {
Trie trie = Trie.builder()
.onlyWholeWords()
.addKeywords(words)
.build();
Collection<Emit> emits = trie.parseText(inputString);
emits.forEach(System.out::println);
boolean found = true;
for(String word : words) {
boolean contains = Arrays.toString(emits.toArray()).contains(word);
if (!contains) {
found = false;
break;
}
}
return found;
}
public static boolean containsWordsPatternMatch(String inputString, String[] words) {
StringBuilder regexp = new StringBuilder();
for (String word : words) {
regexp.append("(?=.*").append(word).append(")");
}
Pattern pattern = Pattern.compile(regexp.toString());
return pattern.matcher(inputString).find();
}
public static boolean containsWordsJava8(String inputString, String[] words) {
List<String> inputStringList = Arrays.asList(inputString.split(" "));
List<String> wordsList = Arrays.asList(words);
return wordsList.stream().allMatch(inputStringList::contains);
}
public static boolean containsWordsArray(String inputString, String[] words) {
List<String> inputStringList = Arrays.asList(inputString.split(" "));
List<String> wordsList = Arrays.asList(words);
return inputStringList.containsAll(wordsList);
}
}
@@ -0,0 +1,61 @@
package com.baeldung.string;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Pangram {
private static final int ALPHABET_COUNT = 26;
public static boolean isPangram(String str) {
if (str == null)
return false;
Boolean[] alphabetMarker = new Boolean[ALPHABET_COUNT];
Arrays.fill(alphabetMarker, false);
int alphabetIndex = 0;
String strUpper = str.toUpperCase();
for (int i = 0; i < str.length(); i++) {
if ('A' <= strUpper.charAt(i) && strUpper.charAt(i) <= 'Z') {
alphabetIndex = strUpper.charAt(i) - 'A';
alphabetMarker[alphabetIndex] = true;
}
}
for (boolean index : alphabetMarker) {
if (!index)
return false;
}
return true;
}
public static boolean isPangramWithStreams(String str) {
if (str == null)
return false;
// filtered character stream
String strUpper = str.toUpperCase();
Stream<Character> filteredCharStream = strUpper.chars()
.filter(item -> ((item >= 'A' && item <= 'Z')))
.mapToObj(c -> (char) c);
Map<Character, Boolean> alphabetMap = filteredCharStream.collect(Collectors.toMap(item -> item, k -> Boolean.TRUE, (p1, p2) -> p1));
return (alphabetMap.size() == ALPHABET_COUNT);
}
public static boolean isPerfectPangram(String str) {
if (str == null)
return false;
// filtered character stream
String strUpper = str.toUpperCase();
Stream<Character> filteredCharStream = strUpper.chars()
.filter(item -> ((item >= 'A' && item <= 'Z')))
.mapToObj(c -> (char) c);
Map<Character, Long> alphabetFrequencyMap = filteredCharStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return (alphabetFrequencyMap.size() == ALPHABET_COUNT && alphabetFrequencyMap.values()
.stream()
.allMatch(item -> item == 1));
}
}
@@ -0,0 +1,8 @@
package com.baeldung.string.emptystrings;
class EmptyStringCheck {
boolean isEmptyString(String string) {
return string == null || string.isEmpty();
}
}
@@ -0,0 +1,8 @@
package com.baeldung.string.emptystrings;
class Java5EmptyStringCheck {
boolean isEmptyString(String string) {
return string == null || string.length() == 0;
}
}
@@ -0,0 +1,8 @@
package com.baeldung.string.emptystrings;
class PlainJavaBlankStringCheck {
boolean isBlankString(String string) {
return string == null || string.trim().isEmpty();
}
}
@@ -0,0 +1,14 @@
package com.baeldung.string.emptystrings;
import javax.validation.constraints.Pattern;
class SomeClassWithValidations {
@Pattern(regexp = "\\A(?!\\s*\\Z).+")
private String someString;
SomeClassWithValidations setSomeString(String someString) {
this.someString = someString;
return this;
}
}
@@ -0,0 +1,67 @@
package com.baeldung.string.multiline;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
public class MultiLineString {
String newLine = System.getProperty("line.separator");
public String stringConcatenation() {
return "Get busy living"
.concat(newLine)
.concat("or")
.concat(newLine)
.concat("get busy dying.")
.concat(newLine)
.concat("--Stephen King");
}
public String stringJoin() {
return String.join(newLine,
"Get busy living",
"or",
"get busy dying.",
"--Stephen King");
}
public String stringBuilder() {
return new StringBuilder()
.append("Get busy living")
.append(newLine)
.append("or")
.append(newLine)
.append("get busy dying.")
.append(newLine)
.append("--Stephen King")
.toString();
}
public String stringWriter() {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
printWriter.println("Get busy living");
printWriter.println("or");
printWriter.println("get busy dying.");
printWriter.println("--Stephen King");
return stringWriter.toString();
}
public String guavaJoiner() {
return Joiner.on(newLine).join(ImmutableList.of("Get busy living",
"or",
"get busy dying.",
"--Stephen King"));
}
public String loadFromFile() throws IOException {
return new String(Files.readAllBytes(Paths.get("src/main/resources/stephenking.txt")));
}
}
@@ -0,0 +1,34 @@
package com.baeldung.string.padding;
public class StringPaddingUtil {
public static String padLeftSpaces(String inputString, int length) {
if (inputString.length() >= length) {
return inputString;
}
StringBuilder sb = new StringBuilder();
while (sb.length() < length - inputString.length()) {
sb.append(' ');
}
sb.append(inputString);
return sb.toString();
}
public static String padLeft(String inputString, int length) {
if (inputString.length() >= length) {
return inputString;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(' ');
}
return sb.substring(inputString.length()) + inputString;
}
public static String padLeftZeros(String inputString, int length) {
return String
.format("%1$" + length + "s", inputString)
.replace(' ', '0');
}
}
@@ -0,0 +1,152 @@
package com.baeldung.string.password;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.text.RandomStringGenerator;
import org.passay.CharacterData;
import org.passay.CharacterRule;
import org.passay.EnglishCharacterData;
import org.passay.PasswordGenerator;
public class RandomPasswordGenerator {
/**
* Special characters allowed in password.
*/
public static final String ALLOWED_SPL_CHARACTERS = "!@#$%^&*()_+";
public static final String ERROR_CODE = "ERRONEOUS_SPECIAL_CHARS";
Random random = new SecureRandom();
public String generatePassayPassword() {
PasswordGenerator gen = new PasswordGenerator();
CharacterData lowerCaseChars = EnglishCharacterData.LowerCase;
CharacterRule lowerCaseRule = new CharacterRule(lowerCaseChars);
lowerCaseRule.setNumberOfCharacters(2);
CharacterData upperCaseChars = EnglishCharacterData.UpperCase;
CharacterRule upperCaseRule = new CharacterRule(upperCaseChars);
upperCaseRule.setNumberOfCharacters(2);
CharacterData digitChars = EnglishCharacterData.Digit;
CharacterRule digitRule = new CharacterRule(digitChars);
digitRule.setNumberOfCharacters(2);
CharacterData specialChars = new CharacterData() {
public String getErrorCode() {
return ERROR_CODE;
}
public String getCharacters() {
return ALLOWED_SPL_CHARACTERS;
}
};
CharacterRule splCharRule = new CharacterRule(specialChars);
splCharRule.setNumberOfCharacters(2);
String password = gen.generatePassword(10, splCharRule, lowerCaseRule, upperCaseRule, digitRule);
return password;
}
public String generateCommonTextPassword() {
String pwString = generateRandomSpecialCharacters(2).concat(generateRandomNumbers(2))
.concat(generateRandomAlphabet(2, true))
.concat(generateRandomAlphabet(2, false))
.concat(generateRandomCharacters(2));
List<Character> pwChars = pwString.chars()
.mapToObj(data -> (char) data)
.collect(Collectors.toList());
Collections.shuffle(pwChars);
String password = pwChars.stream()
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
return password;
}
public String generateCommonsLang3Password() {
String upperCaseLetters = RandomStringUtils.random(2, 65, 90, true, true);
String lowerCaseLetters = RandomStringUtils.random(2, 97, 122, true, true);
String numbers = RandomStringUtils.randomNumeric(2);
String specialChar = RandomStringUtils.random(2, 33, 47, false, false);
String totalChars = RandomStringUtils.randomAlphanumeric(2);
String combinedChars = upperCaseLetters.concat(lowerCaseLetters)
.concat(numbers)
.concat(specialChar)
.concat(totalChars);
List<Character> pwdChars = combinedChars.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
Collections.shuffle(pwdChars);
String password = pwdChars.stream()
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
return password;
}
public String generateSecureRandomPassword() {
Stream<Character> pwdStream = Stream.concat(getRandomNumbers(2), Stream.concat(getRandomSpecialChars(2), Stream.concat(getRandomAlphabets(2, true), getRandomAlphabets(4, false))));
List<Character> charList = pwdStream.collect(Collectors.toList());
Collections.shuffle(charList);
String password = charList.stream()
.collect(StringBuilder::new, StringBuilder::append, StringBuilder::append)
.toString();
return password;
}
public String generateRandomSpecialCharacters(int length) {
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(33, 45)
.build();
return pwdGenerator.generate(length);
}
public String generateRandomNumbers(int length) {
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
.build();
return pwdGenerator.generate(length);
}
public String generateRandomCharacters(int length) {
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(48, 57)
.build();
return pwdGenerator.generate(length);
}
public String generateRandomAlphabet(int length, boolean lowerCase) {
int low;
int hi;
if (lowerCase) {
low = 97;
hi = 122;
} else {
low = 65;
hi = 90;
}
RandomStringGenerator pwdGenerator = new RandomStringGenerator.Builder().withinRange(low, hi)
.build();
return pwdGenerator.generate(length);
}
public Stream<Character> getRandomAlphabets(int count, boolean upperCase) {
IntStream characters = null;
if (upperCase) {
characters = random.ints(count, 65, 90);
} else {
characters = random.ints(count, 97, 122);
}
return characters.mapToObj(data -> (char) data);
}
public Stream<Character> getRandomNumbers(int count) {
IntStream numbers = random.ints(count, 48, 57);
return numbers.mapToObj(data -> (char) data);
}
public Stream<Character> getRandomSpecialChars(int count) {
IntStream specialChars = random.ints(count, 33, 45);
return specialChars.mapToObj(data -> (char) data);
}
}
@@ -0,0 +1,73 @@
package com.baeldung.string.performance;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
@Fork(value = 3, warmups = 1)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
public class RemovingStopwordsPerformanceComparison {
private String data;
private List<String> stopwords;
private String stopwordsRegex;
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Setup
public void setup() throws IOException {
data = new String(Files.readAllBytes(Paths.get("src/main/resources/shakespeare-hamlet.txt")));
data = data.toLowerCase();
stopwords = Files.readAllLines(Paths.get("src/main/resources/english_stopwords.txt"));
stopwordsRegex = stopwords.stream().collect(Collectors.joining("|", "\\b(", ")\\b\\s?"));
}
@Benchmark
public String removeManually() {
String[] allWords = data.split(" ");
StringBuilder builder = new StringBuilder();
for(String word:allWords) {
if(! stopwords.contains(word)) {
builder.append(word);
builder.append(' ');
}
}
return builder.toString().trim();
}
@Benchmark
public String removeAll() {
ArrayList<String> allWords = Stream.of(data.split(" "))
.collect(Collectors.toCollection(ArrayList<String>::new));
allWords.removeAll(stopwords);
return allWords.stream().collect(Collectors.joining(" "));
}
@Benchmark
public String replaceRegex() {
return data.replaceAll(stopwordsRegex, "");
}
}
@@ -0,0 +1,103 @@
package com.baeldung.string.removeleadingtrailingchar;
import org.apache.commons.lang3.StringUtils;
import com.google.common.base.CharMatcher;
public class RemoveLeadingAndTrailingZeroes {
public static String removeLeadingZeroesWithStringBuilder(String s) {
StringBuilder sb = new StringBuilder(s);
while (sb.length() > 1 && sb.charAt(0) == '0') {
sb.deleteCharAt(0);
}
return sb.toString();
}
public static String removeTrailingZeroesWithStringBuilder(String s) {
StringBuilder sb = new StringBuilder(s);
while (sb.length() > 1 && sb.charAt(sb.length() - 1) == '0') {
sb.setLength(sb.length() - 1);
}
return sb.toString();
}
public static String removeLeadingZeroesWithSubstring(String s) {
int index = 0;
for (; index < s.length() - 1; index++) {
if (s.charAt(index) != '0') {
break;
}
}
return s.substring(index);
}
public static String removeTrailingZeroesWithSubstring(String s) {
int index = s.length() - 1;
for (; index > 0; index--) {
if (s.charAt(index) != '0') {
break;
}
}
return s.substring(0, index + 1);
}
public static String removeLeadingZeroesWithApacheCommonsStripStart(String s) {
String stripped = StringUtils.stripStart(s, "0");
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeTrailingZeroesWithApacheCommonsStripEnd(String s) {
String stripped = StringUtils.stripEnd(s, "0");
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeLeadingZeroesWithGuavaTrimLeadingFrom(String s) {
String stripped = CharMatcher.is('0')
.trimLeadingFrom(s);
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeTrailingZeroesWithGuavaTrimTrailingFrom(String s) {
String stripped = CharMatcher.is('0')
.trimTrailingFrom(s);
if (stripped.isEmpty() && !s.isEmpty()) {
return "0";
}
return stripped;
}
public static String removeLeadingZeroesWithRegex(String s) {
return s.replaceAll("^0+(?!$)", "");
}
public static String removeTrailingZeroesWithRegex(String s) {
return s.replaceAll("(?!^)0+$", "");
}
}
@@ -0,0 +1,29 @@
package com.baeldung.string.repetition;
public class SubstringRepetition {
public static boolean containsOnlySubstrings(String string) {
if (string.length() < 2) {
return false;
}
StringBuilder substr = new StringBuilder();
for (int i = 0; i < string.length() / 2; i++) {
substr.append(string.charAt(i));
String clearedFromSubstrings = string.replaceAll(substr.toString(), "");
if (clearedFromSubstrings.length() == 0) {
return true;
}
}
return false;
}
public static boolean containsOnlySubstringsEfficient(String string) {
return ((string + string).indexOf(string, 1) != string.length());
}
}
@@ -0,0 +1,56 @@
package com.baeldung.string.reverse;
import org.apache.commons.lang3.StringUtils;
public class ReverseStringExamples {
public static String reverse(String input) {
if (input == null) {
return null;
}
String output = "";
for (int i = input.length() - 1; i >= 0; i--) {
output = output + input.charAt(i);
}
return output;
}
public static String reverseUsingStringBuilder(String input) {
if (input == null) {
return null;
}
StringBuilder output = new StringBuilder(input).reverse();
return output.toString();
}
public static String reverseUsingApacheCommons(String input) {
return StringUtils.reverse(input);
}
public static String reverseTheOrderOfWords(String sentence) {
if (sentence == null) {
return null;
}
StringBuilder output = new StringBuilder();
String[] words = sentence.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
output.append(words[i]);
output.append(" ");
}
return output.toString()
.trim();
}
public static String reverseTheOrderOfWordsUsingApacheCommons(String sentence) {
return StringUtils.reverseDelimited(sentence, ' ');
}
}
@@ -0,0 +1,58 @@
package com.baeldung.string.search.performance;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
/**
* Based on https://github.com/tedyoung/indexof-contains-benchmark
*/
@Fork(5)
@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
public class SubstringSearchPerformanceComparison {
private String message;
private Pattern pattern;
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Setup
public void setup() {
message = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";
pattern = Pattern.compile("(?<!\\S)" + "eiusmod" + "(?!\\S)");
}
@Benchmark
public int indexOf() {
return message.indexOf("eiusmod");
}
@Benchmark
public boolean contains() {
return message.contains("eiusmod");
}
@Benchmark
public boolean containsStringUtilsIgnoreCase() {
return StringUtils.containsIgnoreCase(message, "eiusmod");
}
@Benchmark
public boolean searchWithPattern() {
return pattern.matcher(message).find();
}
}
@@ -0,0 +1,76 @@
package com.baeldung.string.streamtokenizer;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class StreamTokenizerDemo {
private static final String INPUT_FILE = "/stream-tokenizer-example.txt";
private static final int QUOTE_CHARACTER = '\'';
private static final int DOUBLE_QUOTE_CHARACTER = '"';
public static List<Object> streamTokenizerWithDefaultConfiguration(Reader reader) throws IOException {
StreamTokenizer streamTokenizer = new StreamTokenizer(reader);
List<Object> tokens = new ArrayList<>();
int currentToken = streamTokenizer.nextToken();
while (currentToken != StreamTokenizer.TT_EOF) {
if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) {
tokens.add(streamTokenizer.nval);
} else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD
|| streamTokenizer.ttype == QUOTE_CHARACTER
|| streamTokenizer.ttype == DOUBLE_QUOTE_CHARACTER) {
tokens.add(streamTokenizer.sval);
} else {
tokens.add((char) currentToken);
}
currentToken = streamTokenizer.nextToken();
}
return tokens;
}
public static List<Object> streamTokenizerWithCustomConfiguration(Reader reader) throws IOException {
StreamTokenizer streamTokenizer = new StreamTokenizer(reader);
List<Object> tokens = new ArrayList<>();
streamTokenizer.wordChars('!', '-');
streamTokenizer.ordinaryChar('/');
streamTokenizer.commentChar('#');
streamTokenizer.eolIsSignificant(true);
int currentToken = streamTokenizer.nextToken();
while (currentToken != StreamTokenizer.TT_EOF) {
if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER) {
tokens.add(streamTokenizer.nval);
} else if (streamTokenizer.ttype == StreamTokenizer.TT_WORD
|| streamTokenizer.ttype == QUOTE_CHARACTER
|| streamTokenizer.ttype == DOUBLE_QUOTE_CHARACTER) {
tokens.add(streamTokenizer.sval);
} else {
tokens.add((char) currentToken);
}
currentToken = streamTokenizer.nextToken();
}
return tokens;
}
public static Reader createReaderFromFile() throws FileNotFoundException {
String inputFile = StreamTokenizerDemo.class.getResource(INPUT_FILE).getFile();
return new FileReader(inputFile);
}
public static void main(String[] args) throws IOException {
List<Object> tokens1 = streamTokenizerWithDefaultConfiguration(createReaderFromFile());
List<Object> tokens2 = streamTokenizerWithCustomConfiguration(createReaderFromFile());
System.out.println(tokens1);
System.out.println(tokens2);
}
}
@@ -0,0 +1,102 @@
package com.baeldung.stringduplicates;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
public class RemoveDuplicateFromString {
String removeDuplicatesUsingCharArray(String str) {
char[] chars = str.toCharArray();
StringBuilder sb = new StringBuilder();
int repeatedCtr;
for (int i = 0; i < chars.length; i++) {
repeatedCtr = 0;
for (int j = i + 1; j < chars.length; j++) {
if (chars[i] == chars[j]) {
repeatedCtr++;
}
}
if (repeatedCtr == 0) {
sb.append(chars[i]);
}
}
return sb.toString();
}
String removeDuplicatesUsinglinkedHashSet(String str) {
StringBuilder sb = new StringBuilder();
Set<Character> linkedHashSet = new LinkedHashSet<>();
for (int i = 0; i < str.length(); i++) {
linkedHashSet.add(str.charAt(i));
}
for (Character c : linkedHashSet) {
sb.append(c);
}
return sb.toString();
}
String removeDuplicatesUsingSorting(String str) {
StringBuilder sb = new StringBuilder();
if(!str.isEmpty()) {
char[] chars = str.toCharArray();
Arrays.sort(chars);
sb.append(chars[0]);
for (int i = 1; i < chars.length; i++) {
if (chars[i] != chars[i - 1]) {
sb.append(chars[i]);
}
}
}
return sb.toString();
}
String removeDuplicatesUsingHashSet(String str) {
StringBuilder sb = new StringBuilder();
Set<Character> hashSet = new HashSet<>();
for (int i = 0; i < str.length(); i++) {
hashSet.add(str.charAt(i));
}
for (Character c : hashSet) {
sb.append(c);
}
return sb.toString();
}
String removeDuplicatesUsingIndexOf(String str) {
StringBuilder sb = new StringBuilder();
int idx;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
idx = str.indexOf(c, i + 1);
if (idx == -1) {
sb.append(c);
}
}
return sb.toString();
}
String removeDuplicatesUsingDistinct(String str) {
StringBuilder sb = new StringBuilder();
str.chars().distinct().forEach(c -> sb.append((char) c));
return sb.toString();
}
}