formatting work
This commit is contained in:
parent
44bf48068f
commit
034cde6e20
|
@ -18,9 +18,7 @@ public class Dijkstra {
|
|||
while (unsettledNodes.size() != 0) {
|
||||
Node currentNode = getLowestDistanceNode(unsettledNodes);
|
||||
unsettledNodes.remove(currentNode);
|
||||
for (Entry<Node, Integer> adjacencyPair : currentNode
|
||||
.getAdjacentNodes()
|
||||
.entrySet()) {
|
||||
for (Entry<Node, Integer> adjacencyPair : currentNode.getAdjacentNodes().entrySet()) {
|
||||
Node adjacentNode = adjacencyPair.getKey();
|
||||
Integer edgeWeigh = adjacencyPair.getValue();
|
||||
|
||||
|
|
|
@ -55,29 +55,19 @@ public class DijkstraAlgorithmTest {
|
|||
for (Node node : graph.getNodes()) {
|
||||
switch (node.getName()) {
|
||||
case "B":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeB));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeB));
|
||||
break;
|
||||
case "C":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeC));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeC));
|
||||
break;
|
||||
case "D":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeD));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeD));
|
||||
break;
|
||||
case "E":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeE));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeE));
|
||||
break;
|
||||
case "F":
|
||||
assertTrue(node
|
||||
.getShortestPath()
|
||||
.equals(shortestPathForNodeF));
|
||||
assertTrue(node.getShortestPath().equals(shortestPathForNodeF));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -27,17 +27,12 @@ public class BuilderProcessor extends AbstractProcessor {
|
|||
|
||||
Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
|
||||
|
||||
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream()
|
||||
.collect(Collectors.partitioningBy(element ->
|
||||
((ExecutableType) element.asType()).getParameterTypes().size() == 1
|
||||
&& element.getSimpleName().toString().startsWith("set")));
|
||||
Map<Boolean, List<Element>> annotatedMethods = annotatedElements.stream().collect(Collectors.partitioningBy(element -> ((ExecutableType) element.asType()).getParameterTypes().size() == 1 && element.getSimpleName().toString().startsWith("set")));
|
||||
|
||||
List<Element> setters = annotatedMethods.get(true);
|
||||
List<Element> otherMethods = annotatedMethods.get(false);
|
||||
|
||||
otherMethods.forEach(element ->
|
||||
processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
|
||||
"@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||
otherMethods.forEach(element -> processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "@BuilderProperty must be applied to a setXxx method with a single argument", element));
|
||||
|
||||
if (setters.isEmpty()) {
|
||||
continue;
|
||||
|
@ -45,11 +40,7 @@ public class BuilderProcessor extends AbstractProcessor {
|
|||
|
||||
String className = ((TypeElement) setters.get(0).getEnclosingElement()).getQualifiedName().toString();
|
||||
|
||||
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(
|
||||
setter -> setter.getSimpleName().toString(),
|
||||
setter -> ((ExecutableType) setter.asType())
|
||||
.getParameterTypes().get(0).toString()
|
||||
));
|
||||
Map<String, String> setterMap = setters.stream().collect(Collectors.toMap(setter -> setter.getSimpleName().toString(), setter -> ((ExecutableType) setter.asType()).getParameterTypes().get(0).toString()));
|
||||
|
||||
try {
|
||||
writeBuilderFile(className, setterMap);
|
||||
|
|
|
@ -9,10 +9,7 @@ public class PersonBuilderTest {
|
|||
@Test
|
||||
public void whenBuildPersonWithBuilder_thenObjectHasPropertyValues() {
|
||||
|
||||
Person person = new PersonBuilder()
|
||||
.setAge(25)
|
||||
.setName("John")
|
||||
.build();
|
||||
Person person = new PersonBuilder().setAge(25).setName("John").build();
|
||||
|
||||
assertEquals(25, person.getAge());
|
||||
assertEquals("John", person.getName());
|
||||
|
|
|
@ -38,8 +38,7 @@ public class AssertJCoreTest {
|
|||
public void whenCheckingForElement_thenContains() throws Exception {
|
||||
List<String> list = Arrays.asList("1", "2", "3");
|
||||
|
||||
assertThat(list)
|
||||
.contains("1");
|
||||
assertThat(list).contains("1");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -50,12 +49,7 @@ public class AssertJCoreTest {
|
|||
assertThat(list).startsWith("1");
|
||||
assertThat(list).doesNotContainNull();
|
||||
|
||||
assertThat(list)
|
||||
.isNotEmpty()
|
||||
.contains("1")
|
||||
.startsWith("1")
|
||||
.doesNotContainNull()
|
||||
.containsSequence("2", "3");
|
||||
assertThat(list).isNotEmpty().contains("1").startsWith("1").doesNotContainNull().containsSequence("2", "3");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -67,11 +61,7 @@ public class AssertJCoreTest {
|
|||
public void whenCheckingCharacter_thenIsUnicode() throws Exception {
|
||||
char someCharacter = 'c';
|
||||
|
||||
assertThat(someCharacter)
|
||||
.isNotEqualTo('a')
|
||||
.inUnicode()
|
||||
.isGreaterThanOrEqualTo('b')
|
||||
.isLowerCase();
|
||||
assertThat(someCharacter).isNotEqualTo('a').inUnicode().isGreaterThanOrEqualTo('b').isLowerCase();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -94,11 +84,7 @@ public class AssertJCoreTest {
|
|||
final File someFile = File.createTempFile("aaa", "bbb");
|
||||
someFile.deleteOnExit();
|
||||
|
||||
assertThat(someFile)
|
||||
.exists()
|
||||
.isFile()
|
||||
.canRead()
|
||||
.canWrite();
|
||||
assertThat(someFile).exists().isFile().canRead().canWrite();
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -113,20 +99,14 @@ public class AssertJCoreTest {
|
|||
public void whenGivenMap_then() throws Exception {
|
||||
Map<Integer, String> map = Maps.newHashMap(2, "a");
|
||||
|
||||
assertThat(map)
|
||||
.isNotEmpty()
|
||||
.containsKey(2)
|
||||
.doesNotContainKeys(10)
|
||||
.contains(entry(2, "a"));
|
||||
assertThat(map).isNotEmpty().containsKey(2).doesNotContainKeys(10).contains(entry(2, "a"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGivenException_then() throws Exception {
|
||||
Exception ex = new Exception("abc");
|
||||
|
||||
assertThat(ex)
|
||||
.hasNoCause()
|
||||
.hasMessageEndingWith("c");
|
||||
assertThat(ex).hasNoCause().hasMessageEndingWith("c");
|
||||
}
|
||||
|
||||
@Ignore // IN ORDER TO TEST, REMOVE THIS LINE
|
||||
|
@ -134,8 +114,6 @@ public class AssertJCoreTest {
|
|||
public void whenRunningAssertion_thenDescribed() throws Exception {
|
||||
Person person = new Person("Alex", 34);
|
||||
|
||||
assertThat(person.getAge())
|
||||
.as("%s's age should be equal to 100")
|
||||
.isEqualTo(100);
|
||||
assertThat(person.getAge()).as("%s's age should be equal to 100").isEqualTo(100);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -26,9 +26,7 @@ public class AssertJGuavaTest {
|
|||
final File temp1 = File.createTempFile("bael", "dung1");
|
||||
final File temp2 = File.createTempFile("bael", "dung2");
|
||||
|
||||
assertThat(Files.asByteSource(temp1))
|
||||
.hasSize(0)
|
||||
.hasSameContentAs(Files.asByteSource(temp2));
|
||||
assertThat(Files.asByteSource(temp1)).hasSize(0).hasSameContentAs(Files.asByteSource(temp2));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -37,11 +35,7 @@ public class AssertJGuavaTest {
|
|||
mmap.put(1, "one");
|
||||
mmap.put(1, "1");
|
||||
|
||||
assertThat(mmap)
|
||||
.hasSize(2)
|
||||
.containsKeys(1)
|
||||
.contains(entry(1, "one"))
|
||||
.contains(entry(1, "1"));
|
||||
assertThat(mmap).hasSize(2).containsKeys(1).contains(entry(1, "one")).contains(entry(1, "1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -62,31 +56,21 @@ public class AssertJGuavaTest {
|
|||
mmap2.put(1, "one");
|
||||
mmap2.put(1, "1");
|
||||
|
||||
assertThat(mmap1)
|
||||
.containsAllEntriesOf(mmap2)
|
||||
.containsAllEntriesOf(mmap1_clone)
|
||||
.hasSameEntriesAs(mmap1_clone);
|
||||
assertThat(mmap1).containsAllEntriesOf(mmap2).containsAllEntriesOf(mmap1_clone).hasSameEntriesAs(mmap1_clone);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenOptional_whenVerifyingContent_thenShouldBeEqual() throws Exception {
|
||||
final Optional<String> something = Optional.of("something");
|
||||
|
||||
assertThat(something)
|
||||
.isPresent()
|
||||
.extractingValue()
|
||||
.isEqualTo("something");
|
||||
assertThat(something).isPresent().extractingValue().isEqualTo("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenRange_whenVerifying_thenShouldBeCorrect() throws Exception {
|
||||
final Range<String> range = Range.openClosed("a", "g");
|
||||
|
||||
assertThat(range)
|
||||
.hasOpenedLowerBound()
|
||||
.isNotEmpty()
|
||||
.hasClosedUpperBound()
|
||||
.contains("b");
|
||||
assertThat(range).hasOpenedLowerBound().isNotEmpty().hasClosedUpperBound().contains("b");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -96,10 +80,7 @@ public class AssertJGuavaTest {
|
|||
map.put(Range.closed(0, 60), "F");
|
||||
map.put(Range.closed(61, 70), "D");
|
||||
|
||||
assertThat(map)
|
||||
.isNotEmpty()
|
||||
.containsKeys(0)
|
||||
.contains(MapEntry.entry(34, "F"));
|
||||
assertThat(map).isNotEmpty().containsKeys(0).contains(MapEntry.entry(34, "F"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -109,13 +90,7 @@ public class AssertJGuavaTest {
|
|||
table.put(1, "A", "PRESENT");
|
||||
table.put(1, "B", "ABSENT");
|
||||
|
||||
assertThat(table)
|
||||
.hasRowCount(1)
|
||||
.containsValues("ABSENT")
|
||||
.containsCell(1, "B", "ABSENT");
|
||||
assertThat(table).hasRowCount(1).containsValues("ABSENT").containsCell(1, "B", "ABSENT");
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -20,20 +20,14 @@ public class AssertJJava8Test {
|
|||
public void givenOptional_shouldAssert() throws Exception {
|
||||
final Optional<String> givenOptional = Optional.of("something");
|
||||
|
||||
assertThat(givenOptional)
|
||||
.isPresent()
|
||||
.hasValue("something");
|
||||
assertThat(givenOptional).isPresent().hasValue("something");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenPredicate_shouldAssert() throws Exception {
|
||||
final Predicate<String> predicate = s -> s.length() > 4;
|
||||
|
||||
assertThat(predicate)
|
||||
.accepts("aaaaa", "bbbbb")
|
||||
.rejects("a", "b")
|
||||
.acceptsAll(asList("aaaaa", "bbbbb"))
|
||||
.rejectsAll(asList("a", "b"));
|
||||
assertThat(predicate).accepts("aaaaa", "bbbbb").rejects("a", "b").acceptsAll(asList("aaaaa", "bbbbb")).rejectsAll(asList("a", "b"));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -41,92 +35,74 @@ public class AssertJJava8Test {
|
|||
final LocalDate givenLocalDate = LocalDate.of(2016, 7, 8);
|
||||
final LocalDate todayDate = LocalDate.now();
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDate.of(2020, 7, 8))
|
||||
.isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||
assertThat(givenLocalDate).isBefore(LocalDate.of(2020, 7, 8)).isAfterOrEqualTo(LocalDate.of(1989, 7, 8));
|
||||
|
||||
assertThat(todayDate)
|
||||
.isAfter(LocalDate.of(1989, 7, 8))
|
||||
.isToday();
|
||||
assertThat(todayDate).isAfter(LocalDate.of(1989, 7, 8)).isToday();
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalDateTime_shouldAssert() throws Exception {
|
||||
final LocalDateTime givenLocalDate = LocalDateTime.of(2016, 7, 8, 12, 0);
|
||||
|
||||
assertThat(givenLocalDate)
|
||||
.isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||
assertThat(givenLocalDate).isBefore(LocalDateTime.of(2020, 7, 8, 11, 2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenLocalTime_shouldAssert() throws Exception {
|
||||
final LocalTime givenLocalTime = LocalTime.of(12, 15);
|
||||
|
||||
assertThat(givenLocalTime)
|
||||
.isAfter(LocalTime.of(1, 0))
|
||||
.hasSameHourAs(LocalTime.of(12, 0));
|
||||
assertThat(givenLocalTime).isAfter(LocalTime.of(1, 0)).hasSameHourAs(LocalTime.of(12, 0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear)
|
||||
.contains(2015);
|
||||
assertThat(givenList).flatExtracting(LocalDate::getYear).contains(2015);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingLeapYear() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::isLeapYear)
|
||||
.contains(true);
|
||||
assertThat(givenList).flatExtracting(LocalDate::isLeapYear).contains(true);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertFlatExtractingClass() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(Object::getClass)
|
||||
.contains(LocalDate.class);
|
||||
assertThat(givenList).flatExtracting(Object::getClass).contains(LocalDate.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldAssertMultipleFlatExtracting() throws Exception {
|
||||
final List<LocalDate> givenList = asList(ofYearDay(2016, 5), ofYearDay(2015, 6));
|
||||
|
||||
assertThat(givenList)
|
||||
.flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth)
|
||||
.contains(2015, 6);
|
||||
assertThat(givenList).flatExtracting(LocalDate::getYear, LocalDate::getDayOfMonth).contains(2015, 6);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldSatisfy() throws Exception {
|
||||
final String givenString = "someString";
|
||||
|
||||
assertThat(givenString)
|
||||
.satisfies(s -> {
|
||||
assertThat(s).isNotEmpty();
|
||||
assertThat(s).hasSize(10);
|
||||
});
|
||||
assertThat(givenString).satisfies(s -> {
|
||||
assertThat(s).isNotEmpty();
|
||||
assertThat(s).hasSize(10);
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenString_shouldMatch() throws Exception {
|
||||
final String emptyString = "";
|
||||
|
||||
assertThat(emptyString)
|
||||
.matches(String::isEmpty);
|
||||
assertThat(emptyString).matches(String::isEmpty);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenList_shouldHasOnlyOneElementSatisfying() throws Exception {
|
||||
final List<String> givenList = Arrays.asList("");
|
||||
|
||||
assertThat(givenList)
|
||||
.hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||
assertThat(givenList).hasOnlyOneElementSatisfying(s -> assertThat(s).isEmpty());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,12 +4,12 @@ import com.google.auto.value.AutoValue;
|
|||
|
||||
@AutoValue
|
||||
public abstract class AutoValueMoney {
|
||||
public abstract String getCurrency();
|
||||
public abstract String getCurrency();
|
||||
|
||||
public abstract long getAmount();
|
||||
public abstract long getAmount();
|
||||
|
||||
public static AutoValueMoney create(String currency, long amount) {
|
||||
return new AutoValue_AutoValueMoney(currency, amount);
|
||||
public static AutoValueMoney create(String currency, long amount) {
|
||||
return new AutoValue_AutoValueMoney(currency, amount);
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -4,20 +4,20 @@ import com.google.auto.value.AutoValue;
|
|||
|
||||
@AutoValue
|
||||
public abstract class AutoValueMoneyWithBuilder {
|
||||
public abstract String getCurrency();
|
||||
public abstract String getCurrency();
|
||||
|
||||
public abstract long getAmount();
|
||||
public abstract long getAmount();
|
||||
|
||||
static Builder builder() {
|
||||
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
||||
}
|
||||
static Builder builder() {
|
||||
return new AutoValue_AutoValueMoneyWithBuilder.Builder();
|
||||
}
|
||||
|
||||
@AutoValue.Builder
|
||||
abstract static class Builder {
|
||||
abstract Builder setCurrency(String currency);
|
||||
@AutoValue.Builder
|
||||
abstract static class Builder {
|
||||
abstract Builder setCurrency(String currency);
|
||||
|
||||
abstract Builder setAmount(long amount);
|
||||
abstract Builder setAmount(long amount);
|
||||
|
||||
abstract AutoValueMoneyWithBuilder build();
|
||||
}
|
||||
abstract AutoValueMoneyWithBuilder build();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -3,49 +3,49 @@ package com.baeldung.autovalue;
|
|||
import java.util.Objects;
|
||||
|
||||
public final class Foo {
|
||||
private final String text;
|
||||
private final int number;
|
||||
private final String text;
|
||||
private final int number;
|
||||
|
||||
public Foo(String text, int number) {
|
||||
this.text = text;
|
||||
this.number = number;
|
||||
}
|
||||
public Foo(String text, int number) {
|
||||
this.text = text;
|
||||
this.number = number;
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
public int getNumber() {
|
||||
return number;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(text, number);
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(text, number);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [text=" + text + ", number=" + number + "]";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Foo [text=" + text + ", number=" + number + "]";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Foo other = (Foo) obj;
|
||||
if (number != other.number)
|
||||
return false;
|
||||
if (text == null) {
|
||||
if (other.text != null)
|
||||
return false;
|
||||
} else if (!text.equals(other.text))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
Foo other = (Foo) obj;
|
||||
if (number != other.number)
|
||||
return false;
|
||||
if (text == null) {
|
||||
if (other.text != null)
|
||||
return false;
|
||||
} else if (!text.equals(other.text))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,52 +1,53 @@
|
|||
package com.baeldung.autovalue;
|
||||
|
||||
public final class ImmutableMoney {
|
||||
private final long amount;
|
||||
private final String currency;
|
||||
public ImmutableMoney(long amount, String currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (int) (amount ^ (amount >>> 32));
|
||||
result = prime * result
|
||||
+ ((currency == null) ? 0 : currency.hashCode());
|
||||
return result;
|
||||
}
|
||||
private final long amount;
|
||||
private final String currency;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
ImmutableMoney other = (ImmutableMoney) obj;
|
||||
if (amount != other.amount)
|
||||
return false;
|
||||
if (currency == null) {
|
||||
if (other.currency != null)
|
||||
return false;
|
||||
} else if (!currency.equals(other.currency))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
public ImmutableMoney(long amount, String currency) {
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int prime = 31;
|
||||
int result = 1;
|
||||
result = prime * result + (int) (amount ^ (amount >>> 32));
|
||||
result = prime * result + ((currency == null) ? 0 : currency.hashCode());
|
||||
return result;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (this == obj)
|
||||
return true;
|
||||
if (obj == null)
|
||||
return false;
|
||||
if (getClass() != obj.getClass())
|
||||
return false;
|
||||
ImmutableMoney other = (ImmutableMoney) obj;
|
||||
if (amount != other.amount)
|
||||
return false;
|
||||
if (currency == null) {
|
||||
if (other.currency != null)
|
||||
return false;
|
||||
} else if (!currency.equals(other.currency))
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency
|
||||
+ "]";
|
||||
}
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,35 +1,34 @@
|
|||
package com.baeldung.autovalue;
|
||||
|
||||
public class MutableMoney {
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MutableMoney [amount=" + amount + ", currency=" + currency
|
||||
+ "]";
|
||||
}
|
||||
@Override
|
||||
public String toString() {
|
||||
return "MutableMoney [amount=" + amount + ", currency=" + currency + "]";
|
||||
}
|
||||
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
public long getAmount() {
|
||||
return amount;
|
||||
}
|
||||
|
||||
public void setAmount(long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
public void setAmount(long amount) {
|
||||
this.amount = amount;
|
||||
}
|
||||
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
public String getCurrency() {
|
||||
return currency;
|
||||
}
|
||||
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
public void setCurrency(String currency) {
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
private long amount;
|
||||
private String currency;
|
||||
private long amount;
|
||||
private String currency;
|
||||
|
||||
public MutableMoney(long amount, String currency) {
|
||||
super();
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
public MutableMoney(long amount, String currency) {
|
||||
super();
|
||||
this.amount = amount;
|
||||
this.currency = currency;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -5,55 +5,59 @@ import static org.junit.Assert.*;
|
|||
import org.junit.Test;
|
||||
|
||||
public class MoneyUnitTest {
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
||||
MutableMoney m2 = new MutableMoney(10000, "USD");
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyObjects_whenEqualityTestFails_thenCorrect() {
|
||||
MutableMoney m1 = new MutableMoney(10000, "USD");
|
||||
MutableMoney m2 = new MutableMoney(10000, "USD");
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
||||
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
||||
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenTwoSameValueMoneyValueObjects_whenEqualityTestPasses_thenCorrect() {
|
||||
ImmutableMoney m1 = new ImmutableMoney(10000, "USD");
|
||||
ImmutableMoney m2 = new ImmutableMoney(10000, "USD");
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
||||
assertEquals(m.getAmount(), 10000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
@Test
|
||||
public void givenValueTypeWithAutoValue_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoney m = AutoValueMoney.create("USD", 10000);
|
||||
assertEquals(m.getAmount(), 10000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
@Test
|
||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertEquals(m.getAmount(), 5000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
@Test
|
||||
public void given2EqualValueTypesWithAutoValue_whenEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("USD", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2DifferentValueTypesWithAutoValue_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoney m1 = AutoValueMoney.create("GBP", 5000);
|
||||
AutoValueMoney m2 = AutoValueMoney.create("USD", 5000);
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2EqualValueTypesWithBuilder_whenEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertTrue(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void given2DifferentValueTypesBuilder_whenNotEqual_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m1 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
AutoValueMoneyWithBuilder m2 = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("GBP").build();
|
||||
assertFalse(m1.equals(m2));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueTypeWithBuilder_whenFieldsCorrectlySet_thenCorrect() {
|
||||
AutoValueMoneyWithBuilder m = AutoValueMoneyWithBuilder.builder().setAmount(5000).setCurrency("USD").build();
|
||||
assertEquals(m.getAmount(), 5000);
|
||||
assertEquals(m.getCurrency(), "USD");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,25 +7,24 @@ import com.baeldung.algorithms.slope_one.SlopeOne;
|
|||
|
||||
public class RunAlgorithm {
|
||||
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
System.out.println(
|
||||
"Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Scanner in = new Scanner(System.in);
|
||||
System.out.println("Run algorithm:");
|
||||
System.out.println("1 - Simulated Annealing");
|
||||
System.out.println("2 - Slope One");
|
||||
int decision = in.nextInt();
|
||||
switch (decision) {
|
||||
case 1:
|
||||
System.out.println("Optimized distance for travel: " + SimulatedAnnealing.simulateAnnealing(10, 10000, 0.9995));
|
||||
break;
|
||||
case 2:
|
||||
SlopeOne.slopeOne(3);
|
||||
break;
|
||||
default:
|
||||
System.out.println("Unknown option");
|
||||
break;
|
||||
}
|
||||
in.close();
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -5,18 +5,18 @@ import lombok.Data;
|
|||
@Data
|
||||
public class City {
|
||||
|
||||
private int x;
|
||||
private int y;
|
||||
private int x;
|
||||
private int y;
|
||||
|
||||
public City() {
|
||||
this.x = (int) (Math.random() * 500);
|
||||
this.y = (int) (Math.random() * 500);
|
||||
}
|
||||
public City() {
|
||||
this.x = (int) (Math.random() * 500);
|
||||
this.y = (int) (Math.random() * 500);
|
||||
}
|
||||
|
||||
public double distanceToCity(City city) {
|
||||
int x = Math.abs(getX() - city.getX());
|
||||
int y = Math.abs(getY() - city.getY());
|
||||
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
||||
}
|
||||
public double distanceToCity(City city) {
|
||||
int x = Math.abs(getX() - city.getX());
|
||||
int y = Math.abs(getY() - city.getY());
|
||||
return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -24,7 +24,7 @@ public class SimulatedAnnealing {
|
|||
}
|
||||
t *= coolingRate;
|
||||
} else {
|
||||
continue;
|
||||
continue;
|
||||
}
|
||||
if (i % 100 == 0) {
|
||||
System.out.println("Iteration #" + i);
|
||||
|
|
|
@ -11,26 +11,25 @@ import lombok.Data;
|
|||
|
||||
@Data
|
||||
public class InputData {
|
||||
|
||||
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"),
|
||||
new Item("Snacks"));
|
||||
|
||||
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
||||
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||
HashMap<Item, Double> newUser;
|
||||
Set<Item> newRecommendationSet;
|
||||
for (int i = 0; i < numberOfUsers; i++) {
|
||||
newUser = new HashMap<Item, Double>();
|
||||
newRecommendationSet = new HashSet<>();
|
||||
for (int j = 0; j < 3; j++) {
|
||||
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
||||
}
|
||||
for (Item item : newRecommendationSet) {
|
||||
newUser.put(item, Math.random());
|
||||
}
|
||||
data.put(new User("User " + i), newUser);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
protected static List<Item> items = Arrays.asList(new Item("Candy"), new Item("Drink"), new Item("Soda"), new Item("Popcorn"), new Item("Snacks"));
|
||||
|
||||
public static Map<User, HashMap<Item, Double>> initializeData(int numberOfUsers) {
|
||||
Map<User, HashMap<Item, Double>> data = new HashMap<>();
|
||||
HashMap<Item, Double> newUser;
|
||||
Set<Item> newRecommendationSet;
|
||||
for (int i = 0; i < numberOfUsers; i++) {
|
||||
newUser = new HashMap<Item, Double>();
|
||||
newRecommendationSet = new HashSet<>();
|
||||
for (int j = 0; j < 3; j++) {
|
||||
newRecommendationSet.add(items.get((int) (Math.random() * 5)));
|
||||
}
|
||||
for (Item item : newRecommendationSet) {
|
||||
newUser.put(item, Math.random());
|
||||
}
|
||||
data.put(new User("User " + i), newUser);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -9,5 +9,5 @@ import lombok.NoArgsConstructor;
|
|||
@AllArgsConstructor
|
||||
public class Item {
|
||||
|
||||
private String itemName;
|
||||
private String itemName;
|
||||
}
|
||||
|
|
|
@ -11,114 +11,114 @@ import java.util.Map.Entry;
|
|||
*/
|
||||
public class SlopeOne {
|
||||
|
||||
private static Map<Item, Map<Item, Double>> diff = new HashMap<>();
|
||||
private static Map<Item, Map<Item, Integer>> freq = new HashMap<>();
|
||||
private static Map<User, HashMap<Item, Double>> inputData;
|
||||
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
||||
private static Map<Item, Map<Item, Double>> diff = new HashMap<>();
|
||||
private static Map<Item, Map<Item, Integer>> freq = new HashMap<>();
|
||||
private static Map<User, HashMap<Item, Double>> inputData;
|
||||
private static Map<User, HashMap<Item, Double>> outputData = new HashMap<>();
|
||||
|
||||
public static void slopeOne(int numberOfUsers) {
|
||||
inputData = InputData.initializeData(numberOfUsers);
|
||||
System.out.println("Slope One - Before the Prediction\n");
|
||||
buildDifferencesMatrix(inputData);
|
||||
System.out.println("\nSlope One - With Predictions\n");
|
||||
predict(inputData);
|
||||
}
|
||||
public static void slopeOne(int numberOfUsers) {
|
||||
inputData = InputData.initializeData(numberOfUsers);
|
||||
System.out.println("Slope One - Before the Prediction\n");
|
||||
buildDifferencesMatrix(inputData);
|
||||
System.out.println("\nSlope One - With Predictions\n");
|
||||
predict(inputData);
|
||||
}
|
||||
|
||||
/**
|
||||
* Based on the available data, calculate the relationships between the
|
||||
* items and number of occurences
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
||||
for (HashMap<Item, Double> user : data.values()) {
|
||||
for (Entry<Item, Double> e : user.entrySet()) {
|
||||
if (!diff.containsKey(e.getKey())) {
|
||||
diff.put(e.getKey(), new HashMap<Item, Double>());
|
||||
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
||||
}
|
||||
for (Entry<Item, Double> e2 : user.entrySet()) {
|
||||
int oldCount = 0;
|
||||
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
||||
}
|
||||
double oldDiff = 0.0;
|
||||
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
||||
}
|
||||
double observedDiff = e.getValue() - e2.getValue();
|
||||
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
||||
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Item j : diff.keySet()) {
|
||||
for (Item i : diff.get(j).keySet()) {
|
||||
double oldValue = diff.get(j).get(i).doubleValue();
|
||||
int count = freq.get(j).get(i).intValue();
|
||||
diff.get(j).put(i, oldValue / count);
|
||||
}
|
||||
}
|
||||
printData(data);
|
||||
}
|
||||
/**
|
||||
* Based on the available data, calculate the relationships between the
|
||||
* items and number of occurences
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void buildDifferencesMatrix(Map<User, HashMap<Item, Double>> data) {
|
||||
for (HashMap<Item, Double> user : data.values()) {
|
||||
for (Entry<Item, Double> e : user.entrySet()) {
|
||||
if (!diff.containsKey(e.getKey())) {
|
||||
diff.put(e.getKey(), new HashMap<Item, Double>());
|
||||
freq.put(e.getKey(), new HashMap<Item, Integer>());
|
||||
}
|
||||
for (Entry<Item, Double> e2 : user.entrySet()) {
|
||||
int oldCount = 0;
|
||||
if (freq.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldCount = freq.get(e.getKey()).get(e2.getKey()).intValue();
|
||||
}
|
||||
double oldDiff = 0.0;
|
||||
if (diff.get(e.getKey()).containsKey(e2.getKey())) {
|
||||
oldDiff = diff.get(e.getKey()).get(e2.getKey()).doubleValue();
|
||||
}
|
||||
double observedDiff = e.getValue() - e2.getValue();
|
||||
freq.get(e.getKey()).put(e2.getKey(), oldCount + 1);
|
||||
diff.get(e.getKey()).put(e2.getKey(), oldDiff + observedDiff);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Item j : diff.keySet()) {
|
||||
for (Item i : diff.get(j).keySet()) {
|
||||
double oldValue = diff.get(j).get(i).doubleValue();
|
||||
int count = freq.get(j).get(i).intValue();
|
||||
diff.get(j).put(i, oldValue / count);
|
||||
}
|
||||
}
|
||||
printData(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Based on existing data predict all missing ratings. If prediction is not
|
||||
* possible, the value will be equal to -1
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
||||
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
||||
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
||||
for (Item j : diff.keySet()) {
|
||||
uFreq.put(j, 0);
|
||||
uPred.put(j, 0.0);
|
||||
}
|
||||
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
||||
for (Item j : e.getValue().keySet()) {
|
||||
for (Item k : diff.keySet()) {
|
||||
try {
|
||||
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
||||
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
||||
uPred.put(k, uPred.get(k) + finalValue);
|
||||
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
||||
} catch (NullPointerException e1) {
|
||||
}
|
||||
}
|
||||
}
|
||||
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
||||
for (Item j : uPred.keySet()) {
|
||||
if (uFreq.get(j) > 0) {
|
||||
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
||||
}
|
||||
}
|
||||
for (Item j : InputData.items) {
|
||||
if (e.getValue().containsKey(j)) {
|
||||
clean.put(j, e.getValue().get(j));
|
||||
} else {
|
||||
clean.put(j, -1.0);
|
||||
}
|
||||
}
|
||||
outputData.put(e.getKey(), clean);
|
||||
}
|
||||
printData(outputData);
|
||||
}
|
||||
/**
|
||||
* Based on existing data predict all missing ratings. If prediction is not
|
||||
* possible, the value will be equal to -1
|
||||
*
|
||||
* @param data
|
||||
* existing user data and their items' ratings
|
||||
*/
|
||||
private static void predict(Map<User, HashMap<Item, Double>> data) {
|
||||
HashMap<Item, Double> uPred = new HashMap<Item, Double>();
|
||||
HashMap<Item, Integer> uFreq = new HashMap<Item, Integer>();
|
||||
for (Item j : diff.keySet()) {
|
||||
uFreq.put(j, 0);
|
||||
uPred.put(j, 0.0);
|
||||
}
|
||||
for (Entry<User, HashMap<Item, Double>> e : data.entrySet()) {
|
||||
for (Item j : e.getValue().keySet()) {
|
||||
for (Item k : diff.keySet()) {
|
||||
try {
|
||||
double predictedValue = diff.get(k).get(j).doubleValue() + e.getValue().get(j).doubleValue();
|
||||
double finalValue = predictedValue * freq.get(k).get(j).intValue();
|
||||
uPred.put(k, uPred.get(k) + finalValue);
|
||||
uFreq.put(k, uFreq.get(k) + freq.get(k).get(j).intValue());
|
||||
} catch (NullPointerException e1) {
|
||||
}
|
||||
}
|
||||
}
|
||||
HashMap<Item, Double> clean = new HashMap<Item, Double>();
|
||||
for (Item j : uPred.keySet()) {
|
||||
if (uFreq.get(j) > 0) {
|
||||
clean.put(j, uPred.get(j).doubleValue() / uFreq.get(j).intValue());
|
||||
}
|
||||
}
|
||||
for (Item j : InputData.items) {
|
||||
if (e.getValue().containsKey(j)) {
|
||||
clean.put(j, e.getValue().get(j));
|
||||
} else {
|
||||
clean.put(j, -1.0);
|
||||
}
|
||||
}
|
||||
outputData.put(e.getKey(), clean);
|
||||
}
|
||||
printData(outputData);
|
||||
}
|
||||
|
||||
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
||||
for (User user : data.keySet()) {
|
||||
System.out.println(user.getUsername() + ":");
|
||||
print(data.get(user));
|
||||
}
|
||||
}
|
||||
private static void printData(Map<User, HashMap<Item, Double>> data) {
|
||||
for (User user : data.keySet()) {
|
||||
System.out.println(user.getUsername() + ":");
|
||||
print(data.get(user));
|
||||
}
|
||||
}
|
||||
|
||||
private static void print(HashMap<Item, Double> hashMap) {
|
||||
NumberFormat formatter = new DecimalFormat("#0.000");
|
||||
for (Item j : hashMap.keySet()) {
|
||||
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
||||
}
|
||||
}
|
||||
private static void print(HashMap<Item, Double> hashMap) {
|
||||
NumberFormat formatter = new DecimalFormat("#0.000");
|
||||
for (Item j : hashMap.keySet()) {
|
||||
System.out.println(" " + j.getItemName() + " --> " + formatter.format(hashMap.get(j).doubleValue()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -8,7 +8,7 @@ import lombok.NoArgsConstructor;
|
|||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class User {
|
||||
|
||||
private String username;
|
||||
|
||||
private String username;
|
||||
|
||||
}
|
||||
|
|
|
@ -23,8 +23,7 @@ public class LogWithChain {
|
|||
try {
|
||||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
throw new TeamLeadUpsetException(
|
||||
"Team lead is not in good mood", e);
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood", e);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -36,9 +35,7 @@ public class LogWithChain {
|
|||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager()
|
||||
throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException(
|
||||
"Girl friend of manager is in bad mood");
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -25,8 +25,7 @@ public class LogWithoutChain {
|
|||
howIsManager();
|
||||
} catch (ManagerUpsetException e) {
|
||||
e.printStackTrace();
|
||||
throw new TeamLeadUpsetException(
|
||||
"Team lead is not in good mood");
|
||||
throw new TeamLeadUpsetException("Team lead is not in good mood");
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -39,9 +38,7 @@ public class LogWithoutChain {
|
|||
}
|
||||
}
|
||||
|
||||
private static void howIsGirlFriendOfManager()
|
||||
throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException(
|
||||
"Girl friend of manager is in bad mood");
|
||||
private static void howIsGirlFriendOfManager() throws GirlFriendOfManagerUpsetException {
|
||||
throw new GirlFriendOfManagerUpsetException("Girl friend of manager is in bad mood");
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,10 +10,7 @@ public class WaitingWorker implements Runnable {
|
|||
private final CountDownLatch callingThreadBlocker;
|
||||
private final CountDownLatch completedThreadCounter;
|
||||
|
||||
public WaitingWorker(final List<String> outputScraper,
|
||||
final CountDownLatch readyThreadCounter,
|
||||
final CountDownLatch callingThreadBlocker,
|
||||
CountDownLatch completedThreadCounter) {
|
||||
public WaitingWorker(final List<String> outputScraper, final CountDownLatch readyThreadCounter, final CountDownLatch callingThreadBlocker, CountDownLatch completedThreadCounter) {
|
||||
|
||||
this.outputScraper = outputScraper;
|
||||
this.readyThreadCounter = readyThreadCounter;
|
||||
|
|
|
@ -5,14 +5,14 @@ import java.util.concurrent.ExecutorService;
|
|||
import java.util.concurrent.Future;
|
||||
|
||||
public class SquareCalculator {
|
||||
|
||||
|
||||
private final ExecutorService executor;
|
||||
|
||||
|
||||
public SquareCalculator(ExecutorService executor) {
|
||||
this.executor = executor;
|
||||
}
|
||||
|
||||
public Future<Integer> calculate(Integer input) {
|
||||
|
||||
public Future<Integer> calculate(Integer input) {
|
||||
return executor.submit(new Callable<Integer>() {
|
||||
@Override
|
||||
public Integer call() throws Exception {
|
||||
|
|
|
@ -10,13 +10,11 @@ public class MyLinkedHashMap<K, V> extends LinkedHashMap<K, V> {
|
|||
*/
|
||||
private static final long serialVersionUID = 1L;
|
||||
private static final int MAX_ENTRIES = 5;
|
||||
|
||||
|
||||
public MyLinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) {
|
||||
super(initialCapacity, loadFactor, accessOrder);
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
protected boolean removeEldestEntry(Map.Entry eldest) {
|
||||
return size() > MAX_ENTRIES;
|
||||
|
|
|
@ -42,136 +42,96 @@ public class Java8CollectorsUnitTest {
|
|||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToList() throws Exception {
|
||||
final List<String> result = givenList
|
||||
.stream()
|
||||
.collect(toList());
|
||||
final List<String> result = givenList.stream().collect(toList());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToList_shouldCollectToSet() throws Exception {
|
||||
final Set<String> result = givenList
|
||||
.stream()
|
||||
.collect(toSet());
|
||||
final Set<String> result = givenList.stream().collect(toSet());
|
||||
|
||||
assertThat(result).containsAll(givenList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToCollection_shouldCollectToCollection() throws Exception {
|
||||
final List<String> result = givenList
|
||||
.stream()
|
||||
.collect(toCollection(LinkedList::new));
|
||||
final List<String> result = givenList.stream().collect(toCollection(LinkedList::new));
|
||||
|
||||
assertThat(result)
|
||||
.containsAll(givenList)
|
||||
.isInstanceOf(LinkedList.class);
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(LinkedList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToImmutableCollection_shouldThrowException() throws Exception {
|
||||
assertThatThrownBy(() -> {
|
||||
givenList
|
||||
.stream()
|
||||
.collect(toCollection(ImmutableList::of));
|
||||
givenList.stream().collect(toCollection(ImmutableList::of));
|
||||
}).isInstanceOf(UnsupportedOperationException.class);
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMap() throws Exception {
|
||||
final Map<String, Integer> result = givenList
|
||||
.stream()
|
||||
.collect(toMap(Function.identity(), String::length));
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length));
|
||||
|
||||
assertThat(result)
|
||||
.containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("ccc", 3)
|
||||
.containsEntry("dd", 2);
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingToMap_shouldCollectToMapMerging() throws Exception {
|
||||
final Map<String, Integer> result = givenList
|
||||
.stream()
|
||||
.collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||
final Map<String, Integer> result = givenList.stream().collect(toMap(Function.identity(), String::length, (i1, i2) -> i1));
|
||||
|
||||
assertThat(result)
|
||||
.containsEntry("a", 1)
|
||||
.containsEntry("bb", 2)
|
||||
.containsEntry("ccc", 3)
|
||||
.containsEntry("dd", 2);
|
||||
assertThat(result).containsEntry("a", 1).containsEntry("bb", 2).containsEntry("ccc", 3).containsEntry("dd", 2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCollectingAndThen_shouldCollect() throws Exception {
|
||||
final List<String> result = givenList
|
||||
.stream()
|
||||
.collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
final List<String> result = givenList.stream().collect(collectingAndThen(toList(), ImmutableList::copyOf));
|
||||
|
||||
assertThat(result)
|
||||
.containsAll(givenList)
|
||||
.isInstanceOf(ImmutableList.class);
|
||||
assertThat(result).containsAll(givenList).isInstanceOf(ImmutableList.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoining_shouldJoin() throws Exception {
|
||||
final String result = givenList
|
||||
.stream()
|
||||
.collect(joining());
|
||||
final String result = givenList.stream().collect(joining());
|
||||
|
||||
assertThat(result).isEqualTo("abbcccdd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparator_shouldJoinWithSeparator() throws Exception {
|
||||
final String result = givenList
|
||||
.stream()
|
||||
.collect(joining(" "));
|
||||
final String result = givenList.stream().collect(joining(" "));
|
||||
|
||||
assertThat(result).isEqualTo("a bb ccc dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenJoiningWithSeparatorAndPrefixAndPostfix_shouldJoinWithSeparatorPrePost() throws Exception {
|
||||
final String result = givenList
|
||||
.stream()
|
||||
.collect(joining(" ", "PRE-", "-POST"));
|
||||
final String result = givenList.stream().collect(joining(" ", "PRE-", "-POST"));
|
||||
|
||||
assertThat(result).isEqualTo("PRE-a bb ccc dd-POST");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPartitioningBy_shouldPartition() throws Exception {
|
||||
final Map<Boolean, List<String>> result = givenList
|
||||
.stream()
|
||||
.collect(partitioningBy(s -> s.length() > 2));
|
||||
final Map<Boolean, List<String>> result = givenList.stream().collect(partitioningBy(s -> s.length() > 2));
|
||||
|
||||
assertThat(result)
|
||||
.containsKeys(true, false)
|
||||
.satisfies(booleanListMap -> {
|
||||
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||
assertThat(result).containsKeys(true, false).satisfies(booleanListMap -> {
|
||||
assertThat(booleanListMap.get(true)).contains("ccc");
|
||||
|
||||
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||
});
|
||||
assertThat(booleanListMap.get(false)).contains("a", "bb", "dd");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCounting_shouldCount() throws Exception {
|
||||
final Long result = givenList
|
||||
.stream()
|
||||
.collect(counting());
|
||||
final Long result = givenList.stream().collect(counting());
|
||||
|
||||
assertThat(result).isEqualTo(4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSummarizing_shouldSummarize() throws Exception {
|
||||
final DoubleSummaryStatistics result = givenList
|
||||
.stream()
|
||||
.collect(summarizingDouble(String::length));
|
||||
final DoubleSummaryStatistics result = givenList.stream().collect(summarizingDouble(String::length));
|
||||
|
||||
assertThat(result.getAverage()).isEqualTo(2);
|
||||
assertThat(result.getCount()).isEqualTo(4);
|
||||
|
@ -182,55 +142,37 @@ public class Java8CollectorsUnitTest {
|
|||
|
||||
@Test
|
||||
public void whenAveraging_shouldAverage() throws Exception {
|
||||
final Double result = givenList
|
||||
.stream()
|
||||
.collect(averagingDouble(String::length));
|
||||
final Double result = givenList.stream().collect(averagingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenSumming_shouldSum() throws Exception {
|
||||
final Double result = givenList
|
||||
.stream()
|
||||
.filter(i -> true)
|
||||
.collect(summingDouble(String::length));
|
||||
final Double result = givenList.stream().filter(i -> true).collect(summingDouble(String::length));
|
||||
|
||||
assertThat(result).isEqualTo(8);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenMaxingBy_shouldMaxBy() throws Exception {
|
||||
final Optional<String> result = givenList
|
||||
.stream()
|
||||
.collect(maxBy(Comparator.naturalOrder()));
|
||||
final Optional<String> result = givenList.stream().collect(maxBy(Comparator.naturalOrder()));
|
||||
|
||||
assertThat(result)
|
||||
.isPresent()
|
||||
.hasValue("dd");
|
||||
assertThat(result).isPresent().hasValue("dd");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGroupingBy_shouldGroupBy() throws Exception {
|
||||
final Map<Integer, Set<String>> result = givenList
|
||||
.stream()
|
||||
.collect(groupingBy(String::length, toSet()));
|
||||
final Map<Integer, Set<String>> result = givenList.stream().collect(groupingBy(String::length, toSet()));
|
||||
|
||||
assertThat(result)
|
||||
.containsEntry(1, newHashSet("a"))
|
||||
.containsEntry(2, newHashSet("bb", "dd"))
|
||||
.containsEntry(3, newHashSet("ccc"));
|
||||
assertThat(result).containsEntry(1, newHashSet("a")).containsEntry(2, newHashSet("bb", "dd")).containsEntry(3, newHashSet("ccc"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCreatingCustomCollector_shouldCollect() throws Exception {
|
||||
final ImmutableSet<String> result = givenList
|
||||
.stream()
|
||||
.collect(toImmutableSet());
|
||||
final ImmutableSet<String> result = givenList.stream().collect(toImmutableSet());
|
||||
|
||||
assertThat(result)
|
||||
.isInstanceOf(ImmutableSet.class)
|
||||
.contains("a", "bb", "ccc", "dd");
|
||||
assertThat(result).isInstanceOf(ImmutableSet.class).contains("a", "bb", "ccc", "dd");
|
||||
|
||||
}
|
||||
|
||||
|
|
|
@ -18,10 +18,7 @@ public class CountdownLatchExampleTest {
|
|||
// Given
|
||||
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||
CountDownLatch countDownLatch = new CountDownLatch(5);
|
||||
List<Thread> workers = Stream
|
||||
.generate(() -> new Thread(new Worker(outputScraper, countDownLatch)))
|
||||
.limit(5)
|
||||
.collect(toList());
|
||||
List<Thread> workers = Stream.generate(() -> new Thread(new Worker(outputScraper, countDownLatch))).limit(5).collect(toList());
|
||||
|
||||
// When
|
||||
workers.forEach(Thread::start);
|
||||
|
@ -30,15 +27,7 @@ public class CountdownLatchExampleTest {
|
|||
|
||||
// Then
|
||||
outputScraper.forEach(Object::toString);
|
||||
assertThat(outputScraper)
|
||||
.containsExactly(
|
||||
"Counted down",
|
||||
"Counted down",
|
||||
"Counted down",
|
||||
"Counted down",
|
||||
"Counted down",
|
||||
"Latch released"
|
||||
);
|
||||
assertThat(outputScraper).containsExactly("Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Latch released");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
@ -46,10 +35,7 @@ public class CountdownLatchExampleTest {
|
|||
// Given
|
||||
List<String> outputScraper = Collections.synchronizedList(new ArrayList<>());
|
||||
CountDownLatch countDownLatch = new CountDownLatch(5);
|
||||
List<Thread> workers = Stream
|
||||
.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch)))
|
||||
.limit(5)
|
||||
.collect(toList());
|
||||
List<Thread> workers = Stream.generate(() -> new Thread(new BrokenWorker(outputScraper, countDownLatch))).limit(5).collect(toList());
|
||||
|
||||
// When
|
||||
workers.forEach(Thread::start);
|
||||
|
@ -66,10 +52,7 @@ public class CountdownLatchExampleTest {
|
|||
CountDownLatch readyThreadCounter = new CountDownLatch(5);
|
||||
CountDownLatch callingThreadBlocker = new CountDownLatch(1);
|
||||
CountDownLatch completedThreadCounter = new CountDownLatch(5);
|
||||
List<Thread> workers = Stream
|
||||
.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter)))
|
||||
.limit(5)
|
||||
.collect(toList());
|
||||
List<Thread> workers = Stream.generate(() -> new Thread(new WaitingWorker(outputScraper, readyThreadCounter, callingThreadBlocker, completedThreadCounter))).limit(5).collect(toList());
|
||||
|
||||
// When
|
||||
workers.forEach(Thread::start);
|
||||
|
@ -81,16 +64,7 @@ public class CountdownLatchExampleTest {
|
|||
|
||||
// Then
|
||||
outputScraper.forEach(Object::toString);
|
||||
assertThat(outputScraper)
|
||||
.containsExactly(
|
||||
"Workers ready",
|
||||
"Counted down",
|
||||
"Counted down",
|
||||
"Counted down",
|
||||
"Counted down",
|
||||
"Counted down",
|
||||
"Workers complete"
|
||||
);
|
||||
assertThat(outputScraper).containsExactly("Workers ready", "Counted down", "Counted down", "Counted down", "Counted down", "Counted down", "Workers complete");
|
||||
}
|
||||
|
||||
}
|
|
@ -47,9 +47,7 @@ public class ConcurrentMapAggregateStatusTest {
|
|||
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||
|
||||
for (int i = 1; i <= MAX_SIZE; i++) {
|
||||
assertEquals("map size should be consistently reliable", i, mapSizes
|
||||
.get(i - 1)
|
||||
.intValue());
|
||||
assertEquals("map size should be consistently reliable", i, mapSizes.get(i - 1).intValue());
|
||||
}
|
||||
assertEquals(MAX_SIZE, concurrentMap.size());
|
||||
}
|
||||
|
@ -71,9 +69,7 @@ public class ConcurrentMapAggregateStatusTest {
|
|||
executorService.shutdown();
|
||||
executorService.awaitTermination(1, TimeUnit.MINUTES);
|
||||
|
||||
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes
|
||||
.get(MAX_SIZE - 1)
|
||||
.intValue());
|
||||
assertNotEquals("map size collected with concurrent updates not reliable", MAX_SIZE, mapSizes.get(MAX_SIZE - 1).intValue());
|
||||
assertEquals(MAX_SIZE, concurrentMap.size());
|
||||
}
|
||||
|
||||
|
|
|
@ -36,9 +36,7 @@ public class ConcurrentMapPerformanceTest {
|
|||
for (int i = 0; i < 4; i++) {
|
||||
executorService.execute(() -> {
|
||||
for (int j = 0; j < 500_000; j++) {
|
||||
int value = ThreadLocalRandom
|
||||
.current()
|
||||
.nextInt(10000);
|
||||
int value = ThreadLocalRandom.current().nextInt(10000);
|
||||
String key = String.valueOf(value);
|
||||
map.put(key, value);
|
||||
map.get(key);
|
||||
|
|
|
@ -16,14 +16,8 @@ public class ConcurretMapMemoryConsistencyTest {
|
|||
public void givenConcurrentMap_whenSumParallel_thenCorrect() throws Exception {
|
||||
Map<String, Integer> map = new ConcurrentHashMap<>();
|
||||
List<Integer> sumList = parallelSum100(map, 1000);
|
||||
assertEquals(1, sumList
|
||||
.stream()
|
||||
.distinct()
|
||||
.count());
|
||||
long wrongResultCount = sumList
|
||||
.stream()
|
||||
.filter(num -> num != 100)
|
||||
.count();
|
||||
assertEquals(1, sumList.stream().distinct().count());
|
||||
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||
assertEquals(0, wrongResultCount);
|
||||
}
|
||||
|
||||
|
@ -31,14 +25,8 @@ public class ConcurretMapMemoryConsistencyTest {
|
|||
public void givenHashtable_whenSumParallel_thenCorrect() throws Exception {
|
||||
Map<String, Integer> map = new Hashtable<>();
|
||||
List<Integer> sumList = parallelSum100(map, 1000);
|
||||
assertEquals(1, sumList
|
||||
.stream()
|
||||
.distinct()
|
||||
.count());
|
||||
long wrongResultCount = sumList
|
||||
.stream()
|
||||
.filter(num -> num != 100)
|
||||
.count();
|
||||
assertEquals(1, sumList.stream().distinct().count());
|
||||
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||
assertEquals(0, wrongResultCount);
|
||||
}
|
||||
|
||||
|
@ -46,14 +34,8 @@ public class ConcurretMapMemoryConsistencyTest {
|
|||
public void givenHashMap_whenSumParallel_thenError() throws Exception {
|
||||
Map<String, Integer> map = new HashMap<>();
|
||||
List<Integer> sumList = parallelSum100(map, 100);
|
||||
assertNotEquals(1, sumList
|
||||
.stream()
|
||||
.distinct()
|
||||
.count());
|
||||
long wrongResultCount = sumList
|
||||
.stream()
|
||||
.filter(num -> num != 100)
|
||||
.count();
|
||||
assertNotEquals(1, sumList.stream().distinct().count());
|
||||
long wrongResultCount = sumList.stream().filter(num -> num != 100).count();
|
||||
assertTrue(wrongResultCount > 0);
|
||||
}
|
||||
|
||||
|
|
|
@ -24,8 +24,7 @@ public class IterableStreamConversionTest {
|
|||
public void whenConvertedToList_thenCorrect() {
|
||||
Iterable<String> iterable = Arrays.asList("Testing", "Iterable", "conversion", "to", "Stream");
|
||||
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false)
|
||||
.map(String::toUpperCase).collect(Collectors.toList());
|
||||
List<String> result = StreamSupport.stream(iterable.spliterator(), false).map(String::toUpperCase).collect(Collectors.toList());
|
||||
|
||||
assertThat(result, contains("TESTING", "ITERABLE", "CONVERSION", "TO", "STREAM"));
|
||||
}
|
||||
|
|
|
@ -201,8 +201,6 @@ public class MapTest {
|
|||
assertEquals("val1", rtnVal);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void whenCallsEqualsOnCollision_thenCorrect() {
|
||||
HashMap<MyKey, String> map = new HashMap<>();
|
||||
|
@ -329,7 +327,7 @@ public class MapTest {
|
|||
map.put(1, "val");
|
||||
map.put(5, "val");
|
||||
map.put(4, "val");
|
||||
|
||||
|
||||
Integer highestKey = map.lastKey();
|
||||
Integer lowestKey = map.firstKey();
|
||||
Set<Integer> keysLessThan3 = map.headMap(3).keySet();
|
||||
|
|
|
@ -1,6 +1,5 @@
|
|||
package com.baeldung.java8;
|
||||
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
@ -28,11 +27,7 @@ public class Java8FindAnyFindFirstTest {
|
|||
@Test
|
||||
public void createParallelStream_whenFindAnyResultIsPresent_thenCorrect() throws Exception {
|
||||
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
|
||||
Optional<Integer> result = list
|
||||
.stream()
|
||||
.parallel()
|
||||
.filter(num -> num < 4)
|
||||
.findAny();
|
||||
Optional<Integer> result = list.stream().parallel().filter(num -> num < 4).findAny();
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
assertThat(result.get(), anyOf(is(1), is(2), is(3)));
|
||||
|
|
|
@ -56,9 +56,7 @@ public class NashornTest {
|
|||
Map<String, Object> map = (Map<String, Object>) obj;
|
||||
|
||||
Assert.assertEquals("hello", map.get("greet"));
|
||||
Assert.assertTrue(List.class.isAssignableFrom(map
|
||||
.get("primes")
|
||||
.getClass()));
|
||||
Assert.assertTrue(List.class.isAssignableFrom(map.get("primes").getClass()));
|
||||
}
|
||||
|
||||
@Test
|
||||
|
|
|
@ -11,16 +11,9 @@ import lombok.Getter;
|
|||
|
||||
@Getter
|
||||
public class BookControllerFeignClientBuilder {
|
||||
private BookClient bookClient = createClient(BookClient.class,
|
||||
"http://localhost:8081/api/books");
|
||||
private BookClient bookClient = createClient(BookClient.class, "http://localhost:8081/api/books");
|
||||
|
||||
private static <T> T createClient(Class<T> type, String uri) {
|
||||
return Feign.builder()
|
||||
.client(new OkHttpClient())
|
||||
.encoder(new GsonEncoder())
|
||||
.decoder(new GsonDecoder())
|
||||
.logger(new Slf4jLogger(type))
|
||||
.logLevel(Logger.Level.FULL)
|
||||
.target(type, uri);
|
||||
return Feign.builder().client(new OkHttpClient()).encoder(new GsonEncoder()).decoder(new GsonDecoder()).logger(new Slf4jLogger(type)).logLevel(Logger.Level.FULL).target(type, uri);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -31,9 +31,7 @@ public class BookClientTest {
|
|||
|
||||
@Test
|
||||
public void givenBookClient_shouldRunSuccessfully() throws Exception {
|
||||
List<Book> books = bookClient.findAll().stream()
|
||||
.map(BookResource::getBook)
|
||||
.collect(Collectors.toList());
|
||||
List<Book> books = bookClient.findAll().stream().map(BookResource::getBook).collect(Collectors.toList());
|
||||
assertTrue(books.size() > 2);
|
||||
log.info("{}", books);
|
||||
}
|
||||
|
|
|
@ -11,12 +11,12 @@ import com.datastax.driver.core.utils.UUIDs;
|
|||
|
||||
public class CassandraClient {
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CassandraClient.class);
|
||||
|
||||
|
||||
public static void main(String args[]) {
|
||||
CassandraConnector connector = new CassandraConnector();
|
||||
connector.connect("127.0.0.1", null);
|
||||
Session session = connector.getSession();
|
||||
|
||||
|
||||
KeyspaceRepository sr = new KeyspaceRepository(session);
|
||||
sr.createKeyspace("library", "SimpleStrategy", 1);
|
||||
sr.useKeyspace("library");
|
||||
|
@ -24,21 +24,21 @@ public class CassandraClient {
|
|||
BookRepository br = new BookRepository(session);
|
||||
br.createTable();
|
||||
br.alterTablebooks("publisher", "text");
|
||||
|
||||
|
||||
br.createTableBooksByTitle();
|
||||
|
||||
|
||||
Book book = new Book(UUIDs.timeBased(), "Effective Java", "Joshua Bloch", "Programming");
|
||||
br.insertBookBatch(book);
|
||||
|
||||
|
||||
br.selectAll().forEach(o -> LOG.info("Title in books: " + o.getTitle()));
|
||||
br.selectAllBookByTitle().forEach(o -> LOG.info("Title in booksByTitle: " + o.getTitle()));
|
||||
|
||||
|
||||
br.deletebookByTitle("Effective Java");
|
||||
br.deleteTable("books");
|
||||
br.deleteTable("booksByTitle");
|
||||
|
||||
sr.deleteKeyspace("library");
|
||||
|
||||
|
||||
connector.close();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -16,14 +16,14 @@ public class Book {
|
|||
|
||||
Book() {
|
||||
}
|
||||
|
||||
|
||||
public Book(UUID id, String title, String author, String subject) {
|
||||
this.id = id;
|
||||
this.title = title;
|
||||
this.author = author;
|
||||
this.subject = subject;
|
||||
}
|
||||
|
||||
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
|
|
@ -11,7 +11,7 @@ import com.datastax.driver.core.Session;
|
|||
public class BookRepository {
|
||||
|
||||
private static final String TABLE_NAME = "books";
|
||||
|
||||
|
||||
private static final String TABLE_NAME_BY_TITLE = TABLE_NAME + "ByTitle";
|
||||
|
||||
private Session session;
|
||||
|
@ -29,7 +29,7 @@ public class BookRepository {
|
|||
final String query = sb.toString();
|
||||
session.execute(query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Creates the books table.
|
||||
*/
|
||||
|
@ -62,7 +62,7 @@ public class BookRepository {
|
|||
final String query = sb.toString();
|
||||
session.execute(query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Insert a row in the table booksByTitle.
|
||||
* @param book
|
||||
|
@ -73,19 +73,15 @@ public class BookRepository {
|
|||
final String query = sb.toString();
|
||||
session.execute(query);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Insert a book into two identical tables using a batch query.
|
||||
*
|
||||
* @param book
|
||||
*/
|
||||
public void insertBookBatch(Book book) {
|
||||
StringBuilder sb = new StringBuilder("BEGIN BATCH ")
|
||||
.append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ")
|
||||
.append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor()).append("', '")
|
||||
.append(book.getSubject()).append("');")
|
||||
.append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ")
|
||||
.append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');")
|
||||
StringBuilder sb = new StringBuilder("BEGIN BATCH ").append("INSERT INTO ").append(TABLE_NAME).append("(id, title, author, subject) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("', '").append(book.getAuthor())
|
||||
.append("', '").append(book.getSubject()).append("');").append("INSERT INTO ").append(TABLE_NAME_BY_TITLE).append("(id, title) ").append("VALUES (").append(book.getId()).append(", '").append(book.getTitle()).append("');")
|
||||
.append("APPLY BATCH;");
|
||||
|
||||
final String query = sb.toString();
|
||||
|
@ -101,7 +97,7 @@ public class BookRepository {
|
|||
StringBuilder sb = new StringBuilder("SELECT * FROM ").append(TABLE_NAME_BY_TITLE).append(" WHERE title = '").append(title).append("';");
|
||||
|
||||
final String query = sb.toString();
|
||||
|
||||
|
||||
ResultSet rs = session.execute(query);
|
||||
|
||||
List<Book> books = new ArrayList<Book>();
|
||||
|
@ -133,7 +129,7 @@ public class BookRepository {
|
|||
}
|
||||
return books;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Select all books from booksByTitle
|
||||
* @return
|
||||
|
|
|
@ -9,7 +9,7 @@ import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
|
|||
@EnableConfigServer
|
||||
@EnableEurekaClient
|
||||
public class ConfigApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ConfigApplication.class, args);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ConfigApplication.class, args);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,18 +12,12 @@ import org.springframework.security.config.annotation.web.configuration.WebSecur
|
|||
public class SecurityConfig extends WebSecurityConfigurerAdapter {
|
||||
|
||||
@Autowired
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
|
||||
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
|
||||
auth.inMemoryAuthentication().withUser("configUser").password("configPassword").roles("SYSTEM");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void configure(HttpSecurity http) throws Exception {
|
||||
http.authorizeRequests()
|
||||
.anyRequest().hasRole("SYSTEM")
|
||||
.and()
|
||||
.httpBasic()
|
||||
.and()
|
||||
.csrf()
|
||||
.disable();
|
||||
http.authorizeRequests().anyRequest().hasRole("SYSTEM").and().httpBasic().and().csrf().disable();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,11 +5,7 @@ import org.springframework.cloud.netflix.feign.FeignClient;
|
|||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
||||
@FeignClient(
|
||||
name = "rest-producer",
|
||||
url = "http://localhost:9090",
|
||||
fallback = GreetingClient.GreetingClientFallback.class
|
||||
)
|
||||
@FeignClient(name = "rest-producer", url = "http://localhost:9090", fallback = GreetingClient.GreetingClientFallback.class)
|
||||
public interface GreetingClient extends GreetingController {
|
||||
@Component
|
||||
public static class GreetingClientFallback implements GreetingClient {
|
||||
|
|
Loading…
Reference in New Issue