Merge remote-tracking branch 'origin/master'

This commit is contained in:
Grzegorz Piwowarek
2017-06-10 11:51:40 +02:00
48 changed files with 1776 additions and 454 deletions
@@ -5,7 +5,6 @@ import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Stack;
import java.util.stream.Collectors;
public class HillClimbing {
public static void main(String[] args) {
@@ -22,7 +21,7 @@ public class HillClimbing {
}
}
public static void printEachStep(State state) {
private static void printEachStep(State state) {
List<Stack<String>> stackList = state.getState();
System.out.println("----------------");
stackList.forEach(stack -> {
@@ -33,8 +32,8 @@ public class HillClimbing {
});
}
public Stack<String> getStackWithValues(String[] blocks) {
Stack<String> stack = new Stack<String>();
private Stack<String> getStackWithValues(String[] blocks) {
Stack<String> stack = new Stack<>();
for (String block : blocks)
stack.push(block);
return stack;
@@ -42,14 +41,9 @@ public class HillClimbing {
/**
* This method prepares path from init state to goal state
*
* @param initStateStack
* @param goalStateStack
* @return
* @throws Exception
*/
public List<State> getRouteWithHillClimbing(Stack<String> initStateStack, Stack<String> goalStateStack) throws Exception {
List<Stack<String>> initStateStackList = new ArrayList<Stack<String>>();
List<Stack<String>> initStateStackList = new ArrayList<>();
initStateStackList.add(initStateStack);
int initStateHeuristics = getHeuristicsValue(initStateStackList, goalStateStack);
State initState = new State(initStateStackList, initStateHeuristics);
@@ -71,57 +65,51 @@ public class HillClimbing {
}
}
if (noStateFound)
throw new Exception("No path found");
return resultPath;
}
/**
* This method finds new state from current state based on goal and
* heuristics
*
* @param currentState
* @param goalStateStack
* @return a next state
*/
public State findNextState(State currentState, Stack<String> goalStateStack) {
List<Stack<String>> listOfStacks = currentState.getState();
int currentStateHeuristics = currentState.getHeuristics();
Optional<State> newState = listOfStacks.stream()
return listOfStacks.stream()
.map(stack -> {
State tempState = null;
List<Stack<String>> tempStackList = new ArrayList<Stack<String>>(listOfStacks);
String block = stack.pop();
if (stack.size() == 0)
tempStackList.remove(stack);
tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack);
if (tempState == null) {
tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack);
}
if (tempState == null)
stack.push(block);
return tempState;
return applyOperationsOnState(listOfStacks, stack, currentStateHeuristics, goalStateStack);
})
.filter(Objects::nonNull)
.findFirst();
return newState.orElse(null);
.findFirst()
.orElse(null);
}
/**
* This method applies operations on the current state to get a new state
*/
public State applyOperationsOnState(List<Stack<String>> listOfStacks, Stack<String> stack, int currentStateHeuristics, Stack<String> goalStateStack) {
State tempState;
List<Stack<String>> tempStackList = new ArrayList<>(listOfStacks);
String block = stack.pop();
if (stack.size() == 0)
tempStackList.remove(stack);
tempState = pushElementToNewStack(tempStackList, block, currentStateHeuristics, goalStateStack);
if (tempState == null) {
tempState = pushElementToExistingStacks(stack, tempStackList, block, currentStateHeuristics, goalStateStack);
}
if (tempState == null)
stack.push(block);
return tempState;
}
/**
* Operation to be applied on a state in order to find new states. This
* operation pushes an element into a new stack
*
* @param currentStackList
* @param block
* @param currentStateHeuristics
* @param goalStateStack
* @return a new state
*/
private State pushElementToNewStack(List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
State newState = null;
Stack<String> newStack = new Stack<String>();
Stack<String> newStack = new Stack<>();
newStack.push(block);
currentStackList.add(newStack);
@@ -138,62 +126,64 @@ public class HillClimbing {
* Operation to be applied on a state in order to find new states. This
* operation pushes an element into one of the other stacks to explore new
* states
*
* @param stack
* @param currentStackList
* @param block
* @param currentStateHeuristics
* @param goalStateStack
* @return a new state
*/
private State pushElementToExistingStacks(Stack currentStack, List<Stack<String>> currentStackList, String block, int currentStateHeuristics, Stack<String> goalStateStack) {
Optional<State> newState = currentStackList.stream()
.filter(stack -> stack != currentStack)
.map(stack -> {
stack.push(block);
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
if (newStateHeuristics > currentStateHeuristics) {
return new State(currentStackList, newStateHeuristics);
}
stack.pop();
return null;
return pushElementToStack(stack, block, currentStackList, currentStateHeuristics, goalStateStack);
})
.filter(Objects::nonNull)
.findFirst();
return newState.orElse(null);
}
/**
* This method pushes a block to the stack and returns new state if its closer to goal
*/
private State pushElementToStack(Stack stack, String block, List<Stack<String>> currentStackList, int currentStateHeuristics, Stack<String> goalStateStack) {
stack.push(block);
int newStateHeuristics = getHeuristicsValue(currentStackList, goalStateStack);
if (newStateHeuristics > currentStateHeuristics) {
return new State(currentStackList, newStateHeuristics);
}
stack.pop();
return null;
}
/**
* This method returns heuristics value for given state with respect to goal
* state
*
* @param currentState
* @param goalStateStack
* @return
*/
public int getHeuristicsValue(List<Stack<String>> currentState, Stack<String> goalStateStack) {
Integer heuristicValue = 0;
Integer heuristicValue;
heuristicValue = currentState.stream()
.mapToInt(stack -> {
int stackHeuristics = 0;
boolean isPositioneCorrect = true;
int goalStartIndex = 0;
for (String currentBlock : stack) {
if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) {
stackHeuristics += goalStartIndex;
} else {
stackHeuristics -= goalStartIndex;
isPositioneCorrect = false;
}
goalStartIndex++;
}
return stackHeuristics;
return getHeuristicsValueForStack(stack, currentState, goalStateStack);
})
.sum();
return heuristicValue;
}
/**
* This method returns heuristics value for a particular stack
*/
public int getHeuristicsValueForStack(Stack<String> stack, List<Stack<String>> currentState, Stack<String> goalStateStack) {
int stackHeuristics = 0;
boolean isPositioneCorrect = true;
int goalStartIndex = 0;
for (String currentBlock : stack) {
if (isPositioneCorrect && currentBlock.equals(goalStateStack.get(goalStartIndex))) {
stackHeuristics += goalStartIndex;
} else {
stackHeuristics -= goalStartIndex;
isPositioneCorrect = false;
}
goalStartIndex++;
}
return stackHeuristics;
}
}
@@ -5,26 +5,23 @@ import java.util.List;
import java.util.Stack;
public class State {
List<Stack<String>> state;
int heuristics;
public State() {
}
private List<Stack<String>> state;
private int heuristics;
public State(List<Stack<String>> state) {
this.state = state;
}
public State(List<Stack<String>> state, int heuristics) {
State(List<Stack<String>> state, int heuristics) {
this.state = state;
this.heuristics = heuristics;
}
public State(State state) {
State(State state) {
if (state != null) {
this.state = new ArrayList<Stack<String>>();
this.state = new ArrayList<>();
for (Stack s : state.getState()) {
Stack s1 = new Stack();
Stack s1;
s1 = (Stack) s.clone();
this.state.add(s1);
}
@@ -36,10 +33,6 @@ public class State {
return state;
}
public void setState(List<Stack<String>> state) {
this.state = state;
}
public int getHeuristics() {
return heuristics;
}
@@ -14,17 +14,17 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class HillClimbingAlgorithmTest {
Stack<String> initStack;
Stack<String> goalStack;
private Stack<String> initStack;
private Stack<String> goalStack;
@Before
public void initStacks() {
String blockArr[] = { "B", "C", "D", "A" };
String goalBlockArr[] = { "A", "B", "C", "D" };
initStack = new Stack<String>();
initStack = new Stack<>();
for (String block : blockArr)
initStack.push(block);
goalStack = new Stack<String>();
goalStack = new Stack<>();
for (String block : goalBlockArr)
goalStack.push(block);
}
@@ -48,7 +48,7 @@ public class HillClimbingAlgorithmTest {
@Test
public void givenCurrentState_whenFindNextState_thenBetterHeuristics() {
HillClimbing hillClimbing = new HillClimbing();
List<Stack<String>> initList = new ArrayList<Stack<String>>();
List<Stack<String>> initList = new ArrayList<>();
initList.add(initStack);
State currentState = new State(initList);
currentState.setHeuristics(hillClimbing.getHeuristicsValue(initList, goalStack));
@@ -0,0 +1,43 @@
package com.baeldung.java9.time;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class TimeApi {
public static List<Date> getDatesBetweenUsingJava7(Date startDate, Date endDate) {
List<Date> datesInRange = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
while (calendar.before(endCalendar)) {
Date result = calendar.getTime();
datesInRange.add(result);
calendar.add(Calendar.DATE, 1);
}
return datesInRange;
}
public static List<LocalDate> getDatesBetweenUsingJava8(LocalDate startDate, LocalDate endDate) {
long numOfDaysBetween = ChronoUnit.DAYS.between(startDate, endDate);
return IntStream.iterate(0, i -> i + 1)
.limit(numOfDaysBetween)
.mapToObj(i -> startDate.plusDays(i))
.collect(Collectors.toList());
}
public static List<LocalDate> getDatesBetweenUsingJava9(LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate).collect(Collectors.toList());
}
}
@@ -0,0 +1,58 @@
package com.baeldung.java9.time;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class TimeApiTest {
@Test
public void givenGetDatesBetweenWithUsingJava7_WhenStartEndDate_thenDatesList() {
Date startDate = Calendar.getInstance().getTime();
Calendar endCalendar = Calendar.getInstance();
endCalendar.add(Calendar.DATE, 2);
Date endDate = endCalendar.getTime();
List<Date> dates = TimeApi.getDatesBetweenUsingJava7(startDate, endDate);
assertEquals(dates.size(), 2);
Calendar calendar = Calendar.getInstance();
Date date1 = calendar.getTime();
assertEquals(dates.get(0).getDay(), date1.getDay());
assertEquals(dates.get(0).getMonth(), date1.getMonth());
assertEquals(dates.get(0).getYear(), date1.getYear());
calendar.add(Calendar.DATE, 1);
Date date2 = calendar.getTime();
assertEquals(dates.get(1).getDay(), date2.getDay());
assertEquals(dates.get(1).getMonth(), date2.getMonth());
assertEquals(dates.get(1).getYear(), date2.getYear());
}
@Test
public void givenGetDatesBetweenWithUsingJava8_WhenStartEndDate_thenDatesList() {
LocalDate startDate = LocalDate.now();
LocalDate endDate = LocalDate.now().plusDays(2);
List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava8(startDate, endDate);
assertEquals(dates.size(), 2);
assertEquals(dates.get(0), LocalDate.now());
assertEquals(dates.get(1), LocalDate.now().plusDays(1));
}
@Test
public void givenGetDatesBetweenWithUsingJava9_WhenStartEndDate_thenDatesList() {
LocalDate startDate = LocalDate.now();
LocalDate endDate = LocalDate.now().plusDays(2);
List<LocalDate> dates = TimeApi.getDatesBetweenUsingJava9(startDate, endDate);
assertEquals(dates.size(), 2);
assertEquals(dates.get(0), LocalDate.now());
assertEquals(dates.get(1), LocalDate.now().plusDays(1));
}
}
+2 -1
View File
@@ -17,9 +17,10 @@
# Files generated by integration tests
*.txt
backup-pom.xml
/bin/
/temp
#IntelliJ specific
.idea
.idea/
*.iml
+358 -359
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,23 @@
package com.baeldung.java.reflection;
import java.lang.annotation.Annotation;
public class DynamicGreeter implements Greeter {
private String greet;
public DynamicGreeter(String greet) {
this.greet = greet;
}
@Override
public Class<? extends Annotation> annotationType() {
return DynamicGreeter.class;
}
@Override
public String greet() {
return greet;
}
}
@@ -0,0 +1,10 @@
package com.baeldung.java.reflection;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
public @interface Greeter {
public String greet() default "";
}
@@ -0,0 +1,58 @@
package com.baeldung.java.reflection;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;
public class GreetingAnnotation {
private static final String ANNOTATION_METHOD = "annotationData";
private static final String ANNOTATION_FIELDS = "declaredAnnotations";
private static final String ANNOTATIONS = "annotations";
public static void main(String ...args) {
Greeter greetings = Greetings.class.getAnnotation(Greeter.class);
System.err.println("Hello there, " + greetings.greet() + " !!");
Greeter targetValue = new DynamicGreeter("Good evening");
//alterAnnotationValueJDK8(Greetings.class, Greeter.class, targetValue);
alterAnnotationValueJDK7(Greetings.class, Greeter.class, targetValue);
greetings = Greetings.class.getAnnotation(Greeter.class);
System.err.println("Hello there, " + greetings.greet() + " !!");
}
@SuppressWarnings("unchecked")
public static void alterAnnotationValueJDK8(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
try {
Method method = Class.class.getDeclaredMethod(ANNOTATION_METHOD, null);
method.setAccessible(true);
Object annotationData = method.invoke(targetClass);
Field annotations = annotationData.getClass().getDeclaredField(ANNOTATIONS);
annotations.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(annotationData);
map.put(targetAnnotation, targetValue);
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
public static void alterAnnotationValueJDK7(Class<?> targetClass, Class<? extends Annotation> targetAnnotation, Annotation targetValue) {
try {
Field annotations = Class.class.getDeclaredField(ANNOTATIONS);
annotations.setAccessible(true);
Map<Class<? extends Annotation>, Annotation> map = (Map<Class<? extends Annotation>, Annotation>) annotations.get(targetClass);
System.out.println(map);
map.put(targetAnnotation, targetValue);
System.out.println(map);
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -0,0 +1,6 @@
package com.baeldung.java.reflection;
@Greeter(greet="Good morning")
public class Greetings {
}
@@ -0,0 +1,58 @@
package com.baeldung.map.iteration;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class MapIteration {
public List<String> iterateUsingEntrySet(Map<String, Integer> map) {
List<String> mapKeyValueList = new ArrayList<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
mapKeyValueList.add(entry.getKey() + ":" + entry.getValue());
}
return mapKeyValueList;
}
public List<String> iterateUsingLambda(Map<String, Integer> map) {
List<String> mapKeyValueList = new ArrayList<>();
map.forEach((k, v) -> mapKeyValueList.add(k + ":" + v));
return mapKeyValueList;
}
public List<String> iterateUsingIteratorAndEntry(Map<String, Integer> map) {
ArrayList<String> mapKeyValueList = new ArrayList<>();
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> pair = iterator.next();
mapKeyValueList.add(pair.getKey() + ":" + pair.getValue());
}
return mapKeyValueList;
}
public List<String> iterateUsingKeySetAndForeach(Map<String, Integer> map) {
List<String> mapKeyValueList = new ArrayList<>();
for (String key : map.keySet()) {
mapKeyValueList.add(key + ":" + map.get(key));
}
return mapKeyValueList;
}
public List<String> iterateUsingStreamAPI(Map<String, Integer> map) {
ArrayList<String> mapKeyValueList = new ArrayList<>();
map.entrySet().stream().forEach(e -> mapKeyValueList.add(e.getKey() + ":" + e.getValue()));
return mapKeyValueList;
}
public ArrayList<String> iterateKeys(Map<String, Integer> map) {
ArrayList<String> mapKeyList = new ArrayList<>();
for (String key : map.keySet()) {
mapKeyList.add(key);
}
return mapKeyList;
}
}
@@ -0,0 +1,43 @@
package com.baeldung.reflection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class BaeldungReflectionUtils {
private static final Logger LOG = LoggerFactory.getLogger(BaeldungReflectionUtils.class);
public static List<String> getNullPropertiesList(Customer customer) throws Exception {
PropertyDescriptor[] propDescArr = Introspector.getBeanInfo(Customer.class, Object.class).getPropertyDescriptors();
List<PropertyDescriptor> propDescList = Arrays.asList(propDescArr);
List<String> nullProps = propDescList.stream()
.filter(nulls(customer))
.map(PropertyDescriptor::getName)
.collect(Collectors.toList());
return nullProps;
}
private static Predicate<PropertyDescriptor> nulls(Customer customer) {
Predicate<PropertyDescriptor> isNull = pd -> {
Method getterMethod = pd.getReadMethod();
boolean result = false;
try {
result = (getterMethod != null && getterMethod.invoke(customer) == null);
} catch (Exception e) {
LOG.error("error invoking getter method");
}
return result;
};
return isNull;
}
}
@@ -0,0 +1,58 @@
package com.baeldung.reflection;
public class Customer {
private Integer id;
private String name;
private String emailId;
private Long phoneNumber;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Customer [id=").append(id).append(", name=").append(name).append(", emailId=").append(emailId).append(", phoneNumber=")
.append(phoneNumber).append("]");
return builder.toString();
}
public Customer(Integer id, String name, String emailId, Long phoneNumber) {
super();
this.id = id;
this.name = name;
this.emailId = emailId;
this.phoneNumber = phoneNumber;
}
public Long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
@@ -0,0 +1,46 @@
package com.baeldung.string;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.IntStream;
import java.util.stream.Stream;
/**
* Created by smatt on 26/05/2017.
*/
public class StringToCharStream {
public StringToCharStream() {
//let's use the Stream API to manipulate a string
//this will count the occurrence of each character in the test string
System.out.println("Counting Occurrence of Letter");
String testString = "Noww";
//we don't want to use foreach, so . . .
Map<Character, Integer> map = new HashMap<>();
testString.codePoints()
.mapToObj(c -> (char) c)
.filter(c -> Character.isLetter(c))
.forEach(c -> {
if(map.containsKey(c)) {
map.put(c, map.get(c) + 1);
} else {
map.put(c, 1);
}
});
//printing out the result here
System.out.println(map.toString());
}
public static void main(String [] args) {
new StringToCharStream();
}
}
@@ -0,0 +1,69 @@
package com.baeldung.map.iteration;
import static org.junit.Assert.assertTrue;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
public class MapIterationTest {
public static Map<String, Integer> testMap = new HashMap<String, Integer>();
public static String testString1 = "One:1";
public static String testString2 = "Two:2";
public static String testString3 = "Three:3";
@BeforeClass
public static void createTestData() {
testMap.put("One", 1);
testMap.put("Three", 3);
testMap.put("Two", 2);
}
@Test
public void givenMap_whenIterateUsingEntrySetReturnsAllEntries_thenCorrect() {
MapIteration mapIteration = new MapIteration();
List<String> list = mapIteration.iterateUsingEntrySet(testMap);
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
}
@Test
public void givenMap_whenIterateUsingLambdaReturnsAllEntries_thenCorrect() {
MapIteration mapIteration = new MapIteration();
List<String> list = mapIteration.iterateUsingLambda(testMap);
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
}
@Test
public void givenMap_whenIterateUsingIteratorAndEntryReturnsAllEntries_thenCorrect() {
MapIteration mapIteration = new MapIteration();
List<String> list = mapIteration.iterateUsingIteratorAndEntry(testMap);
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
}
@Test
public void givenMap_whenIterateUsingKeySetAndForeachReturnsAllEntries_thenCorrect() {
MapIteration mapIteration = new MapIteration();
List<String> list = mapIteration.iterateUsingKeySetAndForeach(testMap);
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
}
@Test
public void givenMap_whenIterateUsingStreamAPIReturnsAllEntries_thenCorrect() {
MapIteration mapIteration = new MapIteration();
List<String> list = mapIteration.iterateUsingStreamAPI(testMap);
assertTrue((list.contains(testString1)) && (list.contains(testString2)) && (list.contains(testString3)));
}
@Test
public void givenMap_whenIterateUsingKeysReturnsAllKeys_thenCorrect() {
MapIteration mapIteration = new MapIteration();
ArrayList<String> list = mapIteration.iterateKeys(testMap);
assertTrue((list.contains("One")) && (list.contains("Two")) && (list.contains("Three")));
}
}
@@ -0,0 +1,23 @@
package com.baeldung.reflection;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
public class BaeldungReflectionUtilsTest {
@Test
public void givenCustomer_whenAFieldIsNull_thenFieldNameInResult() throws Exception {
Customer customer = new Customer(1, "Himanshu", null, null);
List<String> result = BaeldungReflectionUtils.getNullPropertiesList(customer);
List<String> expectedFieldNames = Arrays.asList("emailId", "phoneNumber");
Assert.assertTrue(result.size() == expectedFieldNames.size());
Assert.assertTrue(result.containsAll(expectedFieldNames));
}
}
@@ -0,0 +1,36 @@
package com.baeldung.string;
import org.junit.Test;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* Created by smatt on 09/06/2017.
*/
public class StringToCharStreamUnitTest {
String testString = "Tests";
@Test
public void givenTestString_whenChars_thenReturnIntStream() {
assertTrue(testString.chars() instanceof IntStream);
}
@Test
public void givenTestString_whenCodePoints_thenReturnIntStream() {
assertTrue(testString.codePoints() instanceof IntStream);
}
@Test
public void givenIntStream_whenMapToObj_thenReturnCharacterStream() {
Stream<Character> characterStream = testString.chars().mapToObj(c -> (char) c);
Stream<Character> characterStream1 = testString.codePoints().mapToObj(c -> (char) c);
assertNotNull("IntStream returned by chars() did not map to Stream<Character>", characterStream);
assertNotNull("IntStream returned by codePoints() did not map to Stream<Character>", characterStream1);
}
}
+1
View File
@@ -0,0 +1 @@
Out of the night that covers me
+10
View File
@@ -0,0 +1,10 @@
GOOD good morning /
GOOD good evening /
GOOD have a good day /
GOOD nice party! /
GOOD fine pants /
BAD nightmare volcano in the sea /
BAD darkest sky /
BAD greed and waste /
BAD army attacks /
BAD bomb explodes /
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+19 -2
View File
@@ -308,11 +308,28 @@
<artifactId>jool</artifactId>
<version>0.9.12</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>${netty.version}</version>
</dependency>
<!-- OpenNLP -->
<dependency>
<groupId>org.apache.opennlp</groupId>
<artifactId>opennlp-tools</artifactId>
<version>1.8.0</version>
</dependency>
</dependencies>
<properties>
<multiverse.version>0.7.0</multiverse.version>
@@ -332,7 +349,7 @@
<commons.io.version>2.5</commons.io.version>
<flink.version>1.2.0</flink.version>
<jackson.version>2.8.5</jackson.version>
<serenity.version>1.4.1-rc.3</serenity.version>
<serenity.version>1.4.0</serenity.version>
<serenity.jbehave.version>1.24.0</serenity.jbehave.version>
<serenity.jira.version>1.1.3-rc.5</serenity.jira.version>
<serenity.plugin.version>1.4.0</serenity.plugin.version>
@@ -340,4 +357,4 @@
<netty.version>4.1.10.Final</netty.version>
</properties>
</project>
</project>
@@ -0,0 +1,12 @@
package com.baeldung.jmh;
import org.openjdk.jmh.annotations.Benchmark;
public class BenchMark {
@Benchmark
public void init() {
}
}
@@ -0,0 +1,14 @@
package com.baeldung.jmh;
import java.io.IOException;
import org.openjdk.jmh.Main;
import org.openjdk.jmh.runner.RunnerException;
public class JmhDemo {
public static void main(String[] args) throws RunnerException, IOException {
Main.main(args);
}
}
@@ -0,0 +1,166 @@
package com.baeldung.opennlp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.logging.Logger;
import opennlp.tools.chunker.ChunkerME;
import opennlp.tools.chunker.ChunkerModel;
import opennlp.tools.cmdline.postag.POSModelLoader;
import opennlp.tools.doccat.DoccatFactory;
import opennlp.tools.doccat.DoccatModel;
import opennlp.tools.doccat.DocumentCategorizerME;
import opennlp.tools.doccat.DocumentSample;
import opennlp.tools.doccat.DocumentSampleStream;
import opennlp.tools.namefind.NameFinderME;
import opennlp.tools.namefind.TokenNameFinderModel;
import opennlp.tools.postag.POSModel;
import opennlp.tools.postag.POSSample;
import opennlp.tools.postag.POSTaggerME;
import opennlp.tools.sentdetect.SentenceDetectorME;
import opennlp.tools.sentdetect.SentenceModel;
import opennlp.tools.tokenize.Tokenizer;
import opennlp.tools.tokenize.TokenizerME;
import opennlp.tools.tokenize.TokenizerModel;
import opennlp.tools.tokenize.WhitespaceTokenizer;
import opennlp.tools.util.InputStreamFactory;
import opennlp.tools.util.InvalidFormatException;
import opennlp.tools.util.ObjectStream;
import opennlp.tools.util.PlainTextByLineStream;
import opennlp.tools.util.Span;
import opennlp.tools.util.TrainingParameters;
public class OpenNLP {
private final static Logger LOGGER = Logger.getLogger(OpenNLP.class.getName());
private final static String text = "To get to the south: Go to the store. Buy a compass. Use the compass. Then walk to the south.";
private final static String sentence[] = new String[] { "James", "Jordan", "live", "in", "Oklahoma", "city", "." };
private DoccatModel docCatModel;
public static void main(String[] args) {
new OpenNLP();
}
public OpenNLP() {
try {
sentenceDetector();
tokenizer();
nameFinder();
locationFinder();
trainDocumentCategorizer();
documentCategorizer();
partOfSpeechTagger();
chunker();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sentenceDetector() throws InvalidFormatException, IOException {
InputStream is = new FileInputStream("OpenNLP/en-sent.bin");
SentenceModel model = new SentenceModel(is);
SentenceDetectorME sdetector = new SentenceDetectorME(model);
String sentences[] = sdetector.sentDetect(text);
Arrays.stream(sentences).forEach(LOGGER::info);
is.close();
}
public void tokenizer() throws InvalidFormatException, IOException {
InputStream is = new FileInputStream("OpenNLP/en-token.bin");
TokenizerModel model = new TokenizerModel(is);
Tokenizer tokenizer = new TokenizerME(model);
String tokens[] = tokenizer.tokenize(text);
Arrays.stream(tokens).forEach(LOGGER::info);
is.close();
}
public static void nameFinder() throws IOException {
InputStream is = new FileInputStream("OpenNLP/en-ner-person.bin");
TokenNameFinderModel model = new TokenNameFinderModel(is);
is.close();
NameFinderME nameFinder = new NameFinderME(model);
Span nameSpans[] = nameFinder.find(sentence);
String[] names = Span.spansToStrings(nameSpans, sentence);
Arrays.stream(names).forEach(LOGGER::info);
}
public static void locationFinder() throws IOException {
InputStream is = new FileInputStream("OpenNLP/en-ner-location.bin");
TokenNameFinderModel model = new TokenNameFinderModel(is);
is.close();
NameFinderME nameFinder = new NameFinderME(model);
Span locationSpans[] = nameFinder.find(sentence);
String[] locations = Span.spansToStrings(locationSpans, sentence);
Arrays.stream(locations).forEach(LOGGER::info);
}
public void trainDocumentCategorizer() {
try {
InputStreamFactory isf = new InputStreamFactory() {
public InputStream createInputStream() throws IOException {
return new FileInputStream("OpenNLP/doc-cat.train");
}
};
ObjectStream<String> lineStream = new PlainTextByLineStream(isf, "UTF-8");
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
DoccatFactory docCatFactory = new DoccatFactory();
docCatModel = DocumentCategorizerME.train("en", sampleStream, TrainingParameters.defaultParams(), docCatFactory);
} catch (IOException e) {
e.printStackTrace();
}
}
public void documentCategorizer() {
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(docCatModel);
double[] outcomes = myCategorizer.categorize(sentence);
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("GOOD")) {
LOGGER.info("Document is positive :) ");
} else {
LOGGER.info("Document is negative :( ");
}
}
public static void partOfSpeechTagger() throws IOException {
try {
POSModel posModel = new POSModelLoader().load(new File("OpenNLP/en-pos-maxent.bin"));
POSTaggerME posTaggerME = new POSTaggerME(posModel);
InputStreamFactory isf = new InputStreamFactory() {
public InputStream createInputStream() throws IOException {
return new FileInputStream("OpenNLP/PartOfSpeechTag.txt");
}
};
ObjectStream<String> lineStream = new PlainTextByLineStream(isf, "UTF-8");
String line;
while ((line = lineStream.read()) != null) {
String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE.tokenize(line);
String[] tags = posTaggerME.tag(whitespaceTokenizerLine);
POSSample posSample = new POSSample(whitespaceTokenizerLine, tags);
LOGGER.info(posSample.toString());
}
lineStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void chunker() throws IOException {
InputStream is = new FileInputStream("OpenNLP/en-chunker.bin");
ChunkerModel cModel = new ChunkerModel(is);
ChunkerME chunkerME = new ChunkerME(cModel);
String[] taggedSentence = new String[] {"Out", "of", "the", "night", "that", "covers", "me"};
String pos[] = new String[] { "IN", "IN", "DT", "NN", "WDT", "VBZ", "PRP"};
String chunks[] = chunkerME.chunk(taggedSentence, pos);
Arrays.stream(chunks).forEach(LOGGER::info);
}
}

Some files were not shown because too many files have changed in this diff Show More