Nauka Streamów na tekście

0

Metoda ma dopisywać do tekstu znaki \ przed każdym znakiem interpunkcyjnym. Dzięki temu możliwe będzie użycie tekstu jako regular expression.
Czy da się mądrzej zaimplementować metodę TransformatorTextForRegex?:

import static org.junit.Assert.assertTrue;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.junit.Test;

public class TransformatorTextForRegexTest {

	@Test
	public void testTransformTextForRegex() {
		// Given:
		String regex = "C++";
		String input = "Programuję w C++, bo R za trudny.";
		String input2 = "Programuję w C, bo R za trudny.";
		
		// When:
		TransformatorTextForRegex ttfr = new TransformatorTextForRegex();
		String regexTransformed = ttfr.transformTextForRegex(regex);
		System.out.println(regexTransformed);
		Matcher m = Pattern.compile(regexTransformed).matcher(input);
		Matcher m2 = Pattern.compile(regexTransformed).matcher(input2);

		// Then:
		assertTrue(m.find());
		assertTrue(!m2.find());
	}
}
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TransformatorTextForRegex {

	public String transformTextForRegex(String text) {
		import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class TransformatorTextForRegex {

		public String transformTextForRegex(String text) {
		return "\\W" + 
				Pattern.compile("")
				.splitAsStream(text)
				.map(x -> Pattern.matches("\\p{Punct}", x) ? "\\" + x : x)
				.collect(Collectors.joining("")) 
				+ "\\W";
	}


}
0

Czemu nie działa?

	public int countOddDigits(int x) {
		String tmp = String.valueOf(x);
		return (int) tmp.chars().filter(a -> Integer.parseInt(a) % 2 == 1).collect(Collectors.counting());

	}

metoda ma zliczać ilość cyfr nieparzystych w liczbie.

tak też ni za cholerę:

public int calculateNumberOfOddDigits(int x) {
		String tmp = String.valueOf(x);
		System.out.println(
				tmp.chars()
				.filter(a -> a % 2 == 1)
				.collect(
						Collectors.groupingBy(
								Function.identity(), Collectors.counting()
								)
						)
				);
return 0;
	}

EDIT:
Ten chars() jest schrzaniony.
Trzeba to zrobić tak:

	public long calculateNumberOfOddDigits(long x) {
        return  Pattern.compile("")
        		.splitAsStream(String.valueOf(x))
        		.filter(a -> Integer.parseInt(a) % 2 == 1)
        		.collect(Collectors.counting());
    }

1 użytkowników online, w tym zalogowanych: 0, gości: 1