Merge remote-tracking branch 'eugenp/master'

This commit is contained in:
DOHA 2018-12-28 21:01:45 +02:00
commit 633890ac3f
863 changed files with 8063 additions and 4389 deletions

48
akka-http/pom.xml Normal file
View File

@ -0,0 +1,48 @@
<?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<artifactId>akka-http</artifactId>
<name>akka-http</name>
<parent>
<artifactId>parent-modules</artifactId>
<groupId>com.baeldung</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http_2.12</artifactId>
<version>${akka.http.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-stream_2.12</artifactId>
<version>2.5.11</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http-jackson_2.12</artifactId>
<version>${akka.http.version}</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-http-testkit_2.12</artifactId>
<version>${akka.http.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<akka.http.version>10.0.11</akka.http.version>
<akka.stream.version>2.5.11</akka.stream.version>
</properties>
</project>

View File

@ -0,0 +1,26 @@
package com.baeldung.akkahttp;
public class User {
private final Long id;
private final String name;
public User() {
this.name = "";
this.id = null;
}
public User(Long id, String name) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
}

View File

@ -0,0 +1,41 @@
package com.baeldung.akkahttp;
import akka.actor.AbstractActor;
import akka.actor.Props;
import akka.japi.pf.FI;
import com.baeldung.akkahttp.UserMessages.ActionPerformed;
import com.baeldung.akkahttp.UserMessages.CreateUserMessage;
import com.baeldung.akkahttp.UserMessages.GetUserMessage;
class UserActor extends AbstractActor {
private UserService userService = new UserService();
static Props props() {
return Props.create(UserActor.class);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(CreateUserMessage.class, handleCreateUser())
.match(GetUserMessage.class, handleGetUser())
.build();
}
private FI.UnitApply<CreateUserMessage> handleCreateUser() {
return createUserMessageMessage -> {
userService.createUser(createUserMessageMessage.getUser());
sender().tell(new ActionPerformed(String.format("User %s created.", createUserMessageMessage.getUser()
.getName())), getSelf());
};
}
private FI.UnitApply<GetUserMessage> handleGetUser() {
return getUserMessageMessage -> {
sender().tell(userService.getUser(getUserMessageMessage.getUserId()), getSelf());
};
}
}

View File

@ -0,0 +1,49 @@
package com.baeldung.akkahttp;
import java.io.Serializable;
public interface UserMessages {
class ActionPerformed implements Serializable {
private static final long serialVersionUID = 1L;
private final String description;
public ActionPerformed(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
}
class CreateUserMessage implements Serializable {
private static final long serialVersionUID = 1L;
private final User user;
public CreateUserMessage(User user) {
this.user = user;
}
public User getUser() {
return user;
}
}
class GetUserMessage implements Serializable {
private static final long serialVersionUID = 1L;
private final Long userId;
public GetUserMessage(Long userId) {
this.userId = userId;
}
public Long getUserId() {
return userId;
}
}
}

View File

@ -0,0 +1,70 @@
package com.baeldung.akkahttp;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.http.javadsl.marshallers.jackson.Jackson;
import akka.http.javadsl.model.StatusCodes;
import akka.http.javadsl.server.HttpApp;
import akka.http.javadsl.server.Route;
import akka.pattern.PatternsCS;
import akka.util.Timeout;
import com.baeldung.akkahttp.UserMessages.ActionPerformed;
import com.baeldung.akkahttp.UserMessages.CreateUserMessage;
import com.baeldung.akkahttp.UserMessages.GetUserMessage;
import scala.concurrent.duration.Duration;
import static akka.http.javadsl.server.PathMatchers.*;
class UserServer extends HttpApp {
private final ActorRef userActor;
Timeout timeout = new Timeout(Duration.create(5, TimeUnit.SECONDS));
UserServer(ActorRef userActor) {
this.userActor = userActor;
}
@Override
public Route routes() {
return path("users", this::postUser)
.orElse(path(segment("users").slash(longSegment()), id ->
route(getUser(id))));
}
private Route getUser(Long id) {
return get(() -> {
CompletionStage<Optional<User>> user = PatternsCS.ask(userActor, new GetUserMessage(id), timeout)
.thenApply(obj -> (Optional<User>) obj);
return onSuccess(() -> user, performed -> {
if (performed.isPresent())
return complete(StatusCodes.OK, performed.get(), Jackson.marshaller());
else
return complete(StatusCodes.NOT_FOUND);
});
});
}
private Route postUser() {
return route(post(() -> entity(Jackson.unmarshaller(User.class), user -> {
CompletionStage<ActionPerformed> userCreated = PatternsCS.ask(userActor, new CreateUserMessage(user), timeout)
.thenApply(obj -> (ActionPerformed) obj);
return onSuccess(() -> userCreated, performed -> {
return complete(StatusCodes.CREATED, performed, Jackson.marshaller());
});
})));
}
public static void main(String[] args) throws Exception {
ActorSystem system = ActorSystem.create("userServer");
ActorRef userActor = system.actorOf(UserActor.props(), "userActor");
UserServer server = new UserServer(userActor);
server.startServer("localhost", 8080, system);
}
}

View File

@ -0,0 +1,35 @@
package com.baeldung.akkahttp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class UserService {
private final static List<User> users = new ArrayList<>();
static {
users.add(new User(1l, "Alice"));
users.add(new User(2l, "Bob"));
users.add(new User(3l, "Chris"));
users.add(new User(4l, "Dick"));
users.add(new User(5l, "Eve"));
users.add(new User(6l, "Finn"));
}
public Optional<User> getUser(Long id) {
return users.stream()
.filter(user -> user.getId()
.equals(id))
.findFirst();
}
public void createUser(User user) {
users.add(user);
}
public List<User> getUsers(){
return users;
}
}

View File

@ -0,0 +1,50 @@
package com.baeldung.akkahttp;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.http.javadsl.model.ContentTypes;
import akka.http.javadsl.model.HttpEntities;
import akka.http.javadsl.model.HttpRequest;
import akka.http.javadsl.testkit.JUnitRouteTest;
import akka.http.javadsl.testkit.TestRoute;
import org.junit.Test;
public class UserServerUnitTest extends JUnitRouteTest {
ActorSystem system = ActorSystem.create("helloAkkaHttpServer");
ActorRef userActorRef = system.actorOf(UserActor.props(), "userActor");
TestRoute appRoute = testRoute(new UserServer(userActorRef).routes());
@Test
public void whenRequest_thenActorResponds() {
appRoute.run(HttpRequest.GET("/users/1"))
.assertEntity(alice())
.assertStatusCode(200);
appRoute.run(HttpRequest.GET("/users/42"))
.assertStatusCode(404);
appRoute.run(HttpRequest.DELETE("/users/1"))
.assertStatusCode(200);
appRoute.run(HttpRequest.DELETE("/users/42"))
.assertStatusCode(200);
appRoute.run(HttpRequest.POST("/users")
.withEntity(HttpEntities.create(ContentTypes.APPLICATION_JSON, zaphod())))
.assertStatusCode(201);
}
private String alice() {
return "{\"id\":1,\"name\":\"Alice\"}";
}
private String zaphod() {
return "{\"id\":42,\"name\":\"Zaphod\"}";
}
}

View File

@ -10,4 +10,6 @@
- [Multi-Swarm Optimization Algorithm in Java](http://www.baeldung.com/java-multi-swarm-algorithm)
- [String Search Algorithms for Large Texts](http://www.baeldung.com/java-full-text-search-algorithms)
- [Check If a String Contains All The Letters of The Alphabet](https://www.baeldung.com/java-string-contains-all-letters)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [Find the Middle Element of a Linked List](http://www.baeldung.com/java-linked-list-middle-element)
- [Calculate Factorial in Java](https://www.baeldung.com/java-calculate-factorial)
- [Find Substrings That Are Palindromes in Java](https://www.baeldung.com/java-palindrome-substrings)

View File

@ -1,4 +1,4 @@
package com.baeldung.string;
package com.baeldung.algorithms.string;
import java.util.HashSet;
import java.util.Set;

View File

@ -1,4 +1,4 @@
package com.baeldung.string;
package com.baeldung.algorithms.string;
import static org.junit.Assert.assertEquals;
import java.util.HashSet;

View File

@ -59,7 +59,7 @@
<properties>
<curator.version>4.0.1</curator.version>
<zookeeper.version>3.4.11</zookeeper.version>
<jackson-databind.version>2.9.4</jackson-databind.version>
<jackson-databind.version>2.9.7</jackson-databind.version>
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>

5
core-java-11/README.md Normal file
View File

@ -0,0 +1,5 @@
### Relevant articles
- [Java 11 Single File Source Code](https://www.baeldung.com/java-single-file-source-code)
- [Java 11 Local Variable Syntax for Lambda Parameters](https://www.baeldung.com/java-var-lambda-params)

View File

@ -0,0 +1,12 @@
#!/usr/local/bin/java --source 11
import java.util.Arrays;
public class Addition
{
public static void main(String[] args) {
System.out.println(Arrays.stream(args)
.mapToInt(Integer::parseInt)
.sum());
}
}

View File

@ -0,0 +1,43 @@
package com.baeldung;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class NewStringAPIUnitTest {
@Test
public void whenRepeatStringTwice_thenGetStringTwice() {
String output = "La ".repeat(2) + "Land";
is(output).equals("La La Land");
}
@Test
public void whenStripString_thenReturnStringWithoutWhitespaces() {
is("\n\t hello \u2005".strip()).equals("hello");
}
@Test
public void whenTrimAdvanceString_thenReturnStringWithWhitespaces() {
is("\n\t hello \u2005".trim()).equals("hello \u2005");
}
@Test
public void whenBlankString_thenReturnTrue() {
assertTrue("\n\t\u2005 ".isBlank());
}
@Test
public void whenMultilineString_thenReturnNonEmptyLineCount() {
String multilineStr = "This is\n \n a multiline\n string.";
long lineCount = multilineStr.lines()
.filter(String::isBlank)
.count();
is(lineCount).equals(3L);
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.optional;
import org.junit.Test;
import java.util.Optional;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Unit tests for {@link Optional} in Java 11.
*/
public class OptionalUnitTest {
@Test
public void givenAnEmptyOptional_isEmpty_thenBehavesAsExpected() {
Optional<String> opt = Optional.of("Baeldung");
assertFalse(opt.isEmpty());
opt = Optional.ofNullable(null);
assertTrue(opt.isEmpty());
}
}

View File

@ -15,7 +15,6 @@
- [Guide to Java 8 Comparator.comparing()](http://www.baeldung.com/java-8-comparator-comparing)
- [Guide To Java 8 Optional](http://www.baeldung.com/java-optional)
- [Guide to the Java 8 forEach](http://www.baeldung.com/foreach-java)
- [Java Base64 Encoding and Decoding](http://www.baeldung.com/java-base64-encode-and-decode)
- [The Difference Between map() and flatMap()](http://www.baeldung.com/java-difference-map-and-flatmap)
- [Static and Default Methods in Interfaces in Java](http://www.baeldung.com/java-static-default-methods)
- [Efficient Word Frequency Calculator in Java](http://www.baeldung.com/java-word-frequency)

View File

@ -0,0 +1,22 @@
package com.baeldung.interfaces;
public interface Electronic {
//Constant variable
public static final String LED = "LED";
//Abstract method
public int getElectricityUse();
// Static method
public static boolean isEnergyEfficient(String electtronicType) {
if (electtronicType.equals(LED)) {
return true;
}
return false;
}
//Default method
public default void printDescription() {
System.out.println("Electronic Description");
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.interfaces;
public class Employee {
private double salary;
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}

View File

@ -0,0 +1,18 @@
package com.baeldung.interfaces;
import java.util.Comparator;
public class EmployeeSalaryComparator implements Comparator<Employee> {
@Override
public int compare(Employee employeeA, Employee employeeB) {
if(employeeA.getSalary() < employeeB.getSalary()){
return -1;
}else if(employeeA.getSalary() > employeeB.getSalary()){
return 1;
}else{
return 0;
}
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.interfaces;
public interface HasColor {
public String getColor();
}

View File

@ -0,0 +1,10 @@
package com.baeldung.interfaces;
import com.baeldung.interfaces.multiinheritance.Transform;
public class Motorcycle implements Transform {
@Override
public void transform() {
// Implementation
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.interfaces;
public class Truck extends Vehicle {
@Override
public void transform() {
// implementation
}
}

View File

@ -0,0 +1,6 @@
package com.baeldung.interfaces;
import com.baeldung.interfaces.multiinheritance.Transform;
public abstract class Vehicle implements Transform {
}

View File

@ -0,0 +1,13 @@
package com.baeldung.interfaces.multiinheritance;
public class Car implements Fly, Transform {
@Override
public void fly() {
System.out.println("I can Fly!!");
}
@Override
public void transform() {
System.out.println("I can Transform!!");
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.interfaces.multiinheritance;
public abstract interface Fly{
void fly();
}

View File

@ -0,0 +1,10 @@
package com.baeldung.interfaces.multiinheritance;
public interface Transform {
void transform();
default void printSpecs(){
System.out.println("Transform Specification");
}
}

View File

@ -0,0 +1,13 @@
package com.baeldung.interfaces.multiinheritance;
public class Vehicle implements Fly, Transform {
@Override
public void fly() {
System.out.println("I can Fly!!");
}
@Override
public void transform() {
System.out.println("I can Transform!!");
}
}

View File

@ -0,0 +1,25 @@
package com.baeldung.interfaces.polymorphysim;
public class Circle implements Shape {
private double radius;
public Circle(double radius){
this.radius = radius;
}
@Override
public String name() {
return "Circle";
}
@Override
public double area() {
return Math.PI * (radius * radius);
}
@Override
public String getColor() {
return "green";
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.interfaces.polymorphysim;
import java.util.ArrayList;
public class DisplayShape {
private ArrayList<Shape> shapes;
public ArrayList<Shape> getShapes() {
return shapes;
}
public DisplayShape() {
shapes = new ArrayList<>();
}
public void add(Shape shape) {
shapes.add(shape);
}
public void display() {
for (Shape shape : shapes) {
System.out.println(shape.name() + " area: " + shape.area());
}
}
}

View File

@ -0,0 +1,23 @@
package com.baeldung.interfaces.polymorphysim;
import java.util.function.Predicate;
public class FunctionalMain {
public static void main(String[] args) {
Shape circleShape = new Circle(2);
Shape squareShape = new Square(2);
DisplayShape DisplayShape = new DisplayShape();
DisplayShape.add(circleShape);
DisplayShape.add(squareShape);
Predicate<Shape> checkArea = (shape) -> shape.area() < 5;
for (Shape shape : DisplayShape.getShapes()) {
if (checkArea.test(shape)) {
System.out.println(shape.name() + " " + shape.area());
}
}
}
}

View File

@ -0,0 +1,15 @@
package com.baeldung.interfaces.polymorphysim;
public class MainPolymorphic {
public static void main(String[] args){
Shape circleShape = new Circle(2);
Shape squareShape = new Square(2);
DisplayShape displayShape = new DisplayShape();
displayShape.add(circleShape);
displayShape.add(squareShape);
displayShape.display();
}
}

View File

@ -0,0 +1,9 @@
package com.baeldung.interfaces.polymorphysim;
import com.baeldung.interfaces.HasColor;
public interface Shape extends HasColor {
public abstract String name();
public abstract double area();
}

View File

@ -0,0 +1,25 @@
package com.baeldung.interfaces.polymorphysim;
public class Square implements Shape {
private double width;
public Square(double width) {
this.width = width;
}
@Override
public String name() {
return "Square";
}
@Override
public double area() {
return width * width;
}
@Override
public String getColor() {
return "red";
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.interfaces;
import com.baeldung.interfaces.polymorphysim.Circle;
import com.baeldung.interfaces.polymorphysim.Shape;
import com.baeldung.interfaces.polymorphysim.Square;
import org.assertj.core.api.Assertions;
import org.junit.Test;
public class PolymorphysimUnitTest {
@Test
public void whenInterfacePointsToCircle_CircleAreaMethodisBeingCalled(){
double expectedArea = 12.566370614359172;
Shape circle = new Circle(2);
double actualArea = circle.area();
Assertions.assertThat(actualArea).isEqualTo(expectedArea);
}
@Test
public void whenInterfacePointsToSquare_SquareAreaMethodisBeingCalled(){
double expectedArea = 4;
Shape square = new Square(2);
double actualArea = square.area();
Assertions.assertThat(actualArea).isEqualTo(expectedArea);
}
}

View File

@ -9,7 +9,6 @@
- [Java 9 Convenience Factory Methods for Collections](http://www.baeldung.com/java-9-collections-factory-methods)
- [New Stream Collectors in Java 9](http://www.baeldung.com/java9-stream-collectors)
- [Java 9 CompletableFuture API Improvements](http://www.baeldung.com/java-9-completablefuture)
- [Spring Security Redirect to the Previous URL After Login](http://www.baeldung.com/spring-security-redirect-login)
- [Java 9 Process API Improvements](http://www.baeldung.com/java-9-process-api)
- [Introduction to Java 9 StackWalking API](http://www.baeldung.com/java-9-stackwalking-api)
- [Introduction to Project Jigsaw](http://www.baeldung.com/project-jigsaw-java-modularity)

View File

@ -7,6 +7,14 @@ public class Employee implements Serializable {
private int id;
private String name;
public Employee() {
}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}

View File

@ -0,0 +1,90 @@
package com.baeldung.sort;
import com.baeldung.arraycopy.model.Employee;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.Comparator;
import java.util.stream.IntStream;
import static org.junit.Assert.assertArrayEquals;
public class ArraySortUnitTest {
private Employee[] employees;
private int[] numbers;
private String[] strings;
private Employee john = new Employee(6, "John");
private Employee mary = new Employee(3, "Mary");
private Employee david = new Employee(4, "David");
@Before
public void setup() {
createEmployeesArray();
createNumbersArray();
createStringArray();
}
private void createEmployeesArray() {
employees = new Employee[]{john, mary, david};
}
private void createNumbersArray() {
numbers = new int[]{-8, 7, 5, 9, 10, -2, 3};
}
private void createStringArray() {
strings = new String[]{"learning", "java", "with", "baeldung"};
}
@Test
public void givenIntArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(numbers);
assertArrayEquals(new int[]{-8, -2, 3, 5, 7, 9, 10}, numbers);
}
@Test
public void givenIntArray_whenSortingDescending_thenCorrectlySorted() {
numbers = IntStream.of(numbers).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
assertArrayEquals(new int[]{10, 9, 7, 5, 3, -2, -8}, numbers);
}
@Test
public void givenStringArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(strings);
assertArrayEquals(new String[]{"baeldung", "java", "learning", "with"}, strings);
}
@Test
public void givenStringArray_whenSortingDescending_thenCorrectlySorted() {
Arrays.sort(strings, Comparator.reverseOrder());
assertArrayEquals(new String[]{"with", "learning", "java", "baeldung"}, strings);
}
@Test
public void givenObjectArray_whenSortingAscending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName));
assertArrayEquals(new Employee[]{david, john, mary}, employees);
}
@Test
public void givenObjectArray_whenSortingDescending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName).reversed());
assertArrayEquals(new Employee[]{mary, john, david}, employees);
}
@Test
public void givenObjectArray_whenSortingMultipleAttributesAscending_thenCorrectlySorted() {
Arrays.sort(employees, Comparator.comparing(Employee::getName).thenComparing(Employee::getId));
assertArrayEquals(new Employee[]{david, john, mary}, employees);
}
}

View File

@ -0,0 +1,28 @@
=========
## Core Java Collections List Cookbooks and Examples
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Random List Element](http://www.baeldung.com/java-random-list-element)
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)

View File

@ -0,0 +1,48 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-collections-list</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-collections-list</name>
<parent>
<groupId>com.baeldung</groupId>
<artifactId>parent-java</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../parent-java</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>${commons-collections4.version}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<properties>
<commons-collections4.version>4.1</commons-collections4.version>
<commons-lang3.version>3.8.1</commons-lang3.version>
<avaitility.version>1.7.0</avaitility.version>
<assertj.version>3.11.1</assertj.version>
<lombok.version>1.16.12</lombok.version>
</properties>
</project>

View File

@ -0,0 +1,37 @@
package com.baeldung.list.multidimensional;
import java.util.ArrayList;
public class ArrayListOfArrayList {
public static void main(String args[]) {
int vertex = 5;
ArrayList<ArrayList<Integer>> graph = new ArrayList<>(vertex);
//Initializing each element of ArrayList with ArrayList
for(int i=0; i< vertex; i++) {
graph.add(new ArrayList<Integer>());
}
//We can add any number of columns to each row
graph.get(0).add(1);
graph.get(0).add(5);
graph.get(1).add(0);
graph.get(1).add(2);
graph.get(2).add(1);
graph.get(2).add(3);
graph.get(3).add(2);
graph.get(3).add(4);
graph.get(4).add(3);
graph.get(4).add(5);
//Printing all the edges
for(int i=0; i<vertex; i++) {
for(int j=0; j<graph.get(i).size(); j++) {
System.out.println("Edge between vertex "+i+"and "+graph.get(i).get(j));
}
}
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.list.multidimensional;
import java.util.ArrayList;
public class ThreeDimensionalArrayList {
public static void main(String args[]) {
int x_axis_length = 2;
int y_axis_length = 2;
int z_axis_length = 2;
ArrayList< ArrayList< ArrayList<String> > > space = new ArrayList<>(x_axis_length);
//Initializing each element of ArrayList with ArrayList< ArrayList<String> >
for(int i=0; i< x_axis_length; i++) {
space.add(new ArrayList< ArrayList<String> >(y_axis_length));
for(int j =0; j< y_axis_length; j++) {
space.get(i).add(new ArrayList<String>(z_axis_length));
}
}
//Set Red color for points (0,0,0) and (0,0,1)
space.get(0).get(0).add("Red");
space.get(0).get(0).add("Red");
//Set Blue color for points (0,1,0) and (0,1,1)
space.get(0).get(1).add("Blue");
space.get(0).get(1).add("Blue");
//Set Green color for points (1,0,0) and (1,0,1)
space.get(1).get(0).add("Green");
space.get(1).get(0).add("Green");
//Set Yellow color for points (1,1,0) and (1,1,1)
space.get(1).get(1).add("Yellow");
space.get(1).get(1).add("Yellow");
//Printing colors for all the points
for(int i=0; i<x_axis_length; i++) {
for(int j=0; j<y_axis_length; j++) {
for(int k=0; k<z_axis_length; k++) {
System.out.println("Color of point ("+i+","+j+","+k+") is :"+space.get(i).get(j).get(k));
}
}
}
}
}

View File

@ -1,4 +1,4 @@
package com.baeldung;
package org.baeldung;
import com.google.common.collect.Lists;
import org.junit.Test;

View File

@ -0,0 +1,47 @@
package org.baeldung.java.lists;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.stream.Collectors;
public class ListJUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
Assert.assertEquals(list1, list2);
Assert.assertNotSame(list1, list2);
Assert.assertNotEquals(list1, list3);
}
@Test
public void whenIntersection_ShouldReturnCommonElements() throws Exception {
List<String> list = Arrays.asList("red", "blue", "blue", "green", "red");
List<String> otherList = Arrays.asList("red", "green", "green", "yellow");
Set<String> commonElements = new HashSet(Arrays.asList("red", "green"));
Set<String> result = list.stream()
.distinct()
.filter(otherList::contains)
.collect(Collectors.toSet());
Assert.assertEquals(commonElements, result);
Set<String> inverseResult = otherList.stream()
.distinct()
.filter(list::contains)
.collect(Collectors.toSet());
Assert.assertEquals(commonElements, inverseResult);
}
}

View File

@ -3,36 +3,21 @@
## Core Java Collections Cookbooks and Examples
### Relevant Articles:
- [Immutable ArrayList in Java](http://www.baeldung.com/java-immutable-list)
- [Guide to the Java ArrayList](http://www.baeldung.com/java-arraylist)
- [Random List Element](http://www.baeldung.com/java-random-list-element)
- [Java - Combine Multiple Collections](http://www.baeldung.com/java-combine-multiple-collections)
- [Removing all nulls from a List in Java](http://www.baeldung.com/java-remove-nulls-from-list)
- [Removing all duplicates from a List in Java](http://www.baeldung.com/java-remove-duplicates-from-list)
- [Flattening Nested Collections in Java](http://www.baeldung.com/java-flatten-nested-collections)
- [HashSet and TreeSet Comparison](http://www.baeldung.com/java-hashset-vs-treeset)
- [Collect a Java Stream to an Immutable Collection](http://www.baeldung.com/java-stream-immutable-collection)
- [Introduction to the Java ArrayDeque](http://www.baeldung.com/java-array-deque)
- [A Guide to HashSet in Java](http://www.baeldung.com/java-hashset)
- [A Guide to TreeSet in Java](http://www.baeldung.com/java-tree-set)
- [How to TDD a List Implementation in Java](http://www.baeldung.com/java-test-driven-list)
- [Getting the Size of an Iterable in Java](http://www.baeldung.com/java-iterable-size)
- [Iterating Backward Through a List](http://www.baeldung.com/java-list-iterate-backwards)
- [How to Filter a Collection in Java](http://www.baeldung.com/java-collection-filtering)
- [Add Multiple Items to an Java ArrayList](http://www.baeldung.com/java-add-items-array-list)
- [Remove the First Element from a List](http://www.baeldung.com/java-remove-first-element-from-list)
- [Initializing HashSet at the Time of Construction](http://www.baeldung.com/java-initialize-hashset)
- [Removing the First Element of an Array](https://www.baeldung.com/java-array-remove-first-element)
- [Fail-Safe Iterator vs Fail-Fast Iterator](http://www.baeldung.com/java-fail-safe-vs-fail-fast-iterator)
- [Shuffling Collections In Java](http://www.baeldung.com/java-shuffle-collection)
- [How to Find an Element in a List with Java](http://www.baeldung.com/find-list-element-java)
- [An Introduction to Java.util.Hashtable Class](http://www.baeldung.com/java-hash-table)
- [Copy a List to Another List in Java](http://www.baeldung.com/java-copy-list-to-another)
- [Finding Max/Min of a List or Collection](http://www.baeldung.com/java-collection-min-max)
- [Java Null-Safe Streams from Collections](https://www.baeldung.com/java-null-safe-streams-from-collections)
- [Remove All Occurrences of a Specific Value from a List](https://www.baeldung.com/java-remove-value-from-list)
- [Thread Safe LIFO Data Structure Implementations](https://www.baeldung.com/java-lifo-thread-safe)
- [Collections.emptyList() vs. New List Instance](https://www.baeldung.com/java-collections-emptylist-new-list)
- [Differences Between Collection.clear() and Collection.removeAll()](https://www.baeldung.com/java-collection-clear-vs-removeall)
- [Performance of contains() in a HashSet vs ArrayList](https://www.baeldung.com/java-hashset-arraylist-contains-performance)
- [Time Complexity of Java Collections](https://www.baeldung.com/java-collections-complexity)
@ -40,15 +25,7 @@
- [An Introduction to Synchronized Java Collections](https://www.baeldung.com/java-synchronized-collections)
- [Guide to EnumSet](https://www.baeldung.com/java-enumset)
- [Removing Elements from Java Collections](https://www.baeldung.com/java-collection-remove-elements)
- [Converting a Collection to ArrayList in Java](https://www.baeldung.com/java-convert-collection-arraylist)
- [Java 8 Streams: Find Items From One List Based On Values From Another List](https://www.baeldung.com/java-streams-find-list-items)
- [Combining Different Types of Collections in Java](https://www.baeldung.com/java-combine-collections)
- [Sorting in Java](http://www.baeldung.com/java-sorting)
- [A Guide to the Java LinkedList](http://www.baeldung.com/java-linkedlist)
- [Java List UnsupportedOperationException](http://www.baeldung.com/java-list-unsupported-operation-exception)
- [Join and Split Arrays and Collections in Java](http://www.baeldung.com/java-join-and-split)
- [Check If Two Lists are Equal in Java](http://www.baeldung.com/java-test-a-list-for-ordinality-and-equality)
- [Java List Initialization in One Line](https://www.baeldung.com/java-init-list-one-line)
- [ClassCastException: Arrays$ArrayList cannot be cast to ArrayList](https://www.baeldung.com/java-classcastexception-arrays-arraylist)
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)
- [Ways to Iterate Over a List in Java](https://www.baeldung.com/java-iterate-list)
- [A Guide to EnumMap](https://www.baeldung.com/java-enum-map)

View File

@ -0,0 +1,98 @@
package com.baeldung.hashmapvshashtable;
import static org.junit.Assert.assertEquals;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Test;
import com.google.common.collect.Lists;
public class HashmapVsHashtableDifferenceUnitTest {
// null values
@Test(expected = NullPointerException.class)
public void givenHashtable_whenAddNullKey_thenNullPointerExceptionThrown() {
Hashtable<String, String> table = new Hashtable<String, String>();
table.put(null, "value");
}
@Test(expected = NullPointerException.class)
public void givenHashtable_whenAddNullValue_thenNullPointerExceptionThrown() {
Hashtable<String, String> table = new Hashtable<String, String>();
table.put("key", null);
}
@Test
public void givenHashmap_whenAddNullKeyAndValue_thenObjectAdded() {
HashMap<String, String> map = new HashMap<String, String>();
map.put(null, "value");
map.put("key1", null);
map.put("key2", null);
assertEquals(3, map.size());
}
// fail-fast iterator
@Test(expected = ConcurrentModificationException.class)
public void givenHashmap_whenModifyUnderlyingCollection_thenConcurrentModificationExceptionThrown() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Iterator<String> iterator = map.keySet().iterator();
while(iterator.hasNext()){
iterator.next();
map.put("key4", "value4");
}
}
@Test
public void givenHashtable_whenModifyUnderlyingCollection_thenItHasNoEffectOnIteratedCollection() {
Hashtable<String, String> table = new Hashtable<String, String>();
table.put("key1", "value1");
table.put("key2", "value2");
List<String> keysSelected = Lists.newArrayList();
Enumeration<String> keys = table.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
keysSelected.add(key);
if (key.equals("key1")) {
table.put("key3", "value3");
}
}
assertEquals(2, keysSelected.size());
}
// synchronized map
@Test
public void givenHashmap_thenCreateSynchronizedMap() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
Set<Entry<String, String>> set = map.entrySet();
synchronized (map) {
Iterator<Entry<String, String>> it = set.iterator();
while(it.hasNext()) {
Map.Entry<String, String> elem = (Map.Entry<String, String>)it.next();
}
}
Map<String, String> syncMap = Collections.synchronizedMap(map);
}
}

View File

@ -1,21 +0,0 @@
package org.baeldung.java.lists;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
public class ListJUnitTest {
private final List<String> list1 = Arrays.asList("1", "2", "3", "4");
private final List<String> list2 = Arrays.asList("1", "2", "3", "4");
private final List<String> list3 = Arrays.asList("1", "2", "4", "3");
@Test
public void whenTestingForEquality_ShouldBeEqual() throws Exception {
Assert.assertEquals(list1, list2);
Assert.assertNotSame(list1, list2);
Assert.assertNotEquals(list1, list3);
}
}

View File

@ -1,34 +1,24 @@
=========
## Core Java Concurrency Examples
## Core Java Concurrency Advanced Examples
### Relevant Articles:
- [Guide To CompletableFuture](http://www.baeldung.com/java-completablefuture)
- [A Guide to the Java ExecutorService](http://www.baeldung.com/java-executor-service-tutorial)
- [Introduction to Thread Pools in Java](http://www.baeldung.com/thread-pool-java-and-guava)
- [Guide to java.util.concurrent.Future](http://www.baeldung.com/java-future)
- [Guide to CountDownLatch in Java](http://www.baeldung.com/java-countdown-latch)
- [Guide to java.util.concurrent.Locks](http://www.baeldung.com/java-concurrent-locks)
- [An Introduction to ThreadLocal in Java](http://www.baeldung.com/java-threadlocal)
- [Difference Between Wait and Sleep in Java](http://www.baeldung.com/java-wait-and-sleep)
- [LongAdder and LongAccumulator in Java](http://www.baeldung.com/java-longadder-and-longaccumulator)
- [The Dining Philosophers Problem in Java](http://www.baeldung.com/java-dining-philoshophers)
- [Guide to the Java Phaser](http://www.baeldung.com/java-phaser)
- [Guide to Synchronized Keyword in Java](http://www.baeldung.com/java-synchronized)
- [An Introduction to Atomic Variables in Java](http://www.baeldung.com/java-atomic-variables)
- [CyclicBarrier in Java](http://www.baeldung.com/java-cyclic-barrier)
- [Guide to Volatile Keyword in Java](http://www.baeldung.com/java-volatile)
- [Overview of the java.util.concurrent](http://www.baeldung.com/java-util-concurrent)
- [Semaphores in Java](http://www.baeldung.com/java-semaphore)
- [Daemon Threads in Java](http://www.baeldung.com/java-daemon-thread)
- [Implementing a Runnable vs Extending a Thread](http://www.baeldung.com/java-runnable-vs-extending-thread)
- [How to Kill a Java Thread](http://www.baeldung.com/java-thread-stop)
- [ExecutorService - Waiting for Threads to Finish](http://www.baeldung.com/java-executor-wait-for-threads)
- [wait and notify() Methods in Java](http://www.baeldung.com/java-wait-notify)
- [Priority-based Job Scheduling in Java](http://www.baeldung.com/java-priority-job-schedule)
- [A Custom Spring SecurityConfigurer](http://www.baeldung.com/spring-security-custom-configurer)
- [Life Cycle of a Thread in Java](http://www.baeldung.com/java-thread-lifecycle)
- [Runnable vs. Callable in Java](http://www.baeldung.com/java-runnable-callable)
- [Brief Introduction to Java Thread.yield()](https://www.baeldung.com/java-thread-yield)
- [Print Even and Odd Numbers Using 2 Threads](https://www.baeldung.com/java-even-odd-numbers-with-2-threads)
- [Java CyclicBarrier vs CountDownLatch](https://www.baeldung.com/java-cyclicbarrier-countdownlatch)
- [Guide to the Fork/Join Framework in Java](http://www.baeldung.com/java-fork-join)
- [A Guide to ThreadLocalRandom in Java](http://www.baeldung.com/java-thread-local-random)
- [The Thread.join() Method in Java](http://www.baeldung.com/java-thread-join)

View File

@ -2,10 +2,10 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.baeldung</groupId>
<artifactId>core-java-concurrency</artifactId>
<artifactId>core-java-concurrency-advanced</artifactId>
<version>0.1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>core-java-concurrency</name>
<name>core-java-concurrency-advanced</name>
<parent>
<groupId>com.baeldung</groupId>
@ -47,10 +47,20 @@
<version>${avaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<version>${jmh-core.version}</version>
</dependency>
<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<version>${jmh-generator-annprocess.version}</version>
</dependency>
</dependencies>
<build>
<finalName>core-java-concurrency</finalName>
<finalName>core-java-concurrency-advanced</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
@ -69,6 +79,8 @@
<!-- testing -->
<assertj.version>3.6.1</assertj.version>
<avaitility.version>1.7.0</avaitility.version>
<jmh-core.version>1.19</jmh-core.version>
<jmh-generator-annprocess.version>1.19</jmh-generator-annprocess.version>
</properties>
</project>

View File

@ -1,13 +1,13 @@
package com.baeldung.concurrent.atomic;
public class SafeCounterWithLock {
private volatile int counter;
int getValue() {
return counter;
}
synchronized void increment() {
counter++;
}
}
package com.baeldung.concurrent.atomic;
public class SafeCounterWithLock {
private volatile int counter;
int getValue() {
return counter;
}
synchronized void increment() {
counter++;
}
}

View File

@ -1,21 +1,21 @@
package com.baeldung.concurrent.atomic;
import java.util.concurrent.atomic.AtomicInteger;
public class SafeCounterWithoutLock {
private final AtomicInteger counter = new AtomicInteger(0);
int getValue() {
return counter.get();
}
void increment() {
while(true) {
int existingValue = getValue();
int newValue = existingValue + 1;
if(counter.compareAndSet(existingValue, newValue)) {
return;
}
}
}
}
package com.baeldung.concurrent.atomic;
import java.util.concurrent.atomic.AtomicInteger;
public class SafeCounterWithoutLock {
private final AtomicInteger counter = new AtomicInteger(0);
int getValue() {
return counter.get();
}
void increment() {
while(true) {
int existingValue = getValue();
int newValue = existingValue + 1;
if(counter.compareAndSet(existingValue, newValue)) {
return;
}
}
}
}

View File

@ -1,13 +1,13 @@
package com.baeldung.concurrent.atomic;
public class UnsafeCounter {
private int counter;
int getValue() {
return counter;
}
void increment() {
counter++;
}
}
package com.baeldung.concurrent.atomic;
public class UnsafeCounter {
private int counter;
int getValue() {
return counter;
}
void increment() {
counter++;
}
}

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