[] - Moved artices / codes from from the core-java related modules
This commit is contained in:
@@ -37,3 +37,9 @@
|
||||
- [How to Convert List to Map in Java](http://www.baeldung.com/java-list-to-map)
|
||||
- [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)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.baeldung.findanelement;
|
||||
|
||||
public class Customer {
|
||||
|
||||
private int id;
|
||||
private String name;
|
||||
|
||||
public Customer(int id, String name) {
|
||||
this.id = id;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public int getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return id * 20;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (obj instanceof Customer) {
|
||||
Customer otherCustomer = (Customer) obj;
|
||||
if (id == otherCustomer.id)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package com.baeldung.findanelement;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.collections4.IterableUtils;
|
||||
|
||||
import com.google.common.base.Predicate;
|
||||
import com.google.common.collect.Iterables;
|
||||
|
||||
public class FindACustomerInGivenList {
|
||||
|
||||
public Customer findUsingGivenIndex(int indexOfCustomer, List<Customer> customers) {
|
||||
if (indexOfCustomer >= 0 && indexOfCustomer < customers.size())
|
||||
return customers.get(indexOfCustomer);
|
||||
return null;
|
||||
}
|
||||
|
||||
public int findUsingIndexOf(Customer customer, List<Customer> customers) {
|
||||
return customers.indexOf(customer);
|
||||
}
|
||||
|
||||
public boolean findUsingContains(Customer customer, List<Customer> customers) {
|
||||
return customers.contains(customer);
|
||||
}
|
||||
|
||||
public Customer findUsingIterator(String name, List<Customer> customers) {
|
||||
Iterator<Customer> iterator = customers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Customer customer = iterator.next();
|
||||
if (customer.getName().equals(name)) {
|
||||
return customer;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Customer findUsingEnhancedForLoop(String name, List<Customer> customers) {
|
||||
for (Customer customer : customers) {
|
||||
if (customer.getName().equals(name)) {
|
||||
return customer;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Customer findUsingStream(String name, List<Customer> customers) {
|
||||
return customers.stream()
|
||||
.filter(customer -> customer.getName().equals(name))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public Customer findUsingParallelStream(String name, List<Customer> customers) {
|
||||
return customers.parallelStream()
|
||||
.filter(customer -> customer.getName().equals(name))
|
||||
.findAny()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
public Customer findUsingGuava(String name, List<Customer> customers) {
|
||||
return Iterables.tryFind(customers, new Predicate<Customer>() {
|
||||
public boolean apply(Customer customer) {
|
||||
return customer.getName().equals(name);
|
||||
}
|
||||
}).orNull();
|
||||
}
|
||||
|
||||
public Customer findUsingApacheCommon(String name, List<Customer> customers) {
|
||||
return IterableUtils.find(customers, new org.apache.commons.collections4.Predicate<Customer>() {
|
||||
public boolean evaluate(Customer customer) {
|
||||
return customer.getName().equals(name);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.baeldung.hashtable;
|
||||
|
||||
public class Word {
|
||||
private String name;
|
||||
|
||||
public Word(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public boolean equals(Object o) {
|
||||
if (o == this)
|
||||
return true;
|
||||
if (!(o instanceof Word))
|
||||
return false;
|
||||
|
||||
Word word = (Word) o;
|
||||
return word.getName().equals(this.name) ? true : false;
|
||||
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return name.hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.baeldung.iterators;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* Source code https://github.com/eugenp/tutorials
|
||||
*
|
||||
* @author Santosh Thakur
|
||||
*/
|
||||
|
||||
public class Iterators {
|
||||
|
||||
public static int failFast1() {
|
||||
ArrayList<Integer> numbers = new ArrayList<>();
|
||||
|
||||
numbers.add(10);
|
||||
numbers.add(20);
|
||||
numbers.add(30);
|
||||
numbers.add(40);
|
||||
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Integer number = iterator.next();
|
||||
numbers.add(50);
|
||||
}
|
||||
|
||||
return numbers.size();
|
||||
}
|
||||
|
||||
public static int failFast2() {
|
||||
ArrayList<Integer> numbers = new ArrayList<>();
|
||||
numbers.add(10);
|
||||
numbers.add(20);
|
||||
numbers.add(30);
|
||||
numbers.add(40);
|
||||
|
||||
Iterator<Integer> iterator = numbers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (iterator.next() == 30) {
|
||||
// will not throw Exception
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("using iterator's remove method = " + numbers);
|
||||
|
||||
iterator = numbers.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
if (iterator.next() == 40) {
|
||||
// will throw Exception on
|
||||
// next call of next() method
|
||||
numbers.remove(2);
|
||||
}
|
||||
}
|
||||
|
||||
return numbers.size();
|
||||
}
|
||||
|
||||
public static int failSafe1() {
|
||||
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
|
||||
|
||||
map.put("First", 10);
|
||||
map.put("Second", 20);
|
||||
map.put("Third", 30);
|
||||
map.put("Fourth", 40);
|
||||
|
||||
Iterator<String> iterator = map.keySet()
|
||||
.iterator();
|
||||
|
||||
while (iterator.hasNext()) {
|
||||
String key = iterator.next();
|
||||
map.put("Fifth", 50);
|
||||
}
|
||||
|
||||
return map.size();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
public class CopyListService {
|
||||
|
||||
public List<Flower> copyListByConstructor(List<Flower> source) {
|
||||
return new ArrayList<Flower>(source);
|
||||
}
|
||||
|
||||
public List<Flower> copyListByConstructorAndEditOneFlowerInTheNewList(List<Flower> source) {
|
||||
List<Flower> flowers = new ArrayList<>(source);
|
||||
if(flowers.size() > 0) {
|
||||
flowers.get(0).setPetals(flowers.get(0).getPetals() * 3);
|
||||
}
|
||||
|
||||
return flowers;
|
||||
}
|
||||
|
||||
public List<Flower> copyListByAddAllMethod(List<Flower> source) {
|
||||
List<Flower> flowers = new ArrayList<>();
|
||||
flowers.addAll(source);
|
||||
return flowers;
|
||||
}
|
||||
|
||||
public List<Flower> copyListByAddAllMethodAndEditOneFlowerInTheNewList(List<Flower> source) {
|
||||
List<Flower> flowers = new ArrayList<>();
|
||||
flowers.addAll(source);
|
||||
|
||||
if(flowers.size() > 0) {
|
||||
flowers.get(0).setPetals(flowers.get(0).getPetals() * 3);
|
||||
}
|
||||
|
||||
return flowers;
|
||||
}
|
||||
|
||||
public List<Integer> copyListByCopyMethod(List<Integer> source, List<Integer> dest) {
|
||||
Collections.copy(dest, source);
|
||||
return dest;
|
||||
}
|
||||
|
||||
public List<Flower> copyListByStream(List<Flower> source) {
|
||||
return source.stream().collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Flower> copyListByStreamAndSkipFirstElement(List<Flower> source) {
|
||||
return source.stream().skip(1).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Flower> copyListByStreamWithFilter(List<Flower> source, Integer moreThanPetals) {
|
||||
return source.stream().filter(f -> f.getPetals() > moreThanPetals).collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Flower> copyListByStreamWithOptional(List<Flower> source) {
|
||||
return Optional.ofNullable(source)
|
||||
.map(List::stream)
|
||||
.orElseGet(Stream::empty)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
public List<Flower> copyListByStreamWithOptionalAndSkip(List<Flower> source) {
|
||||
return Optional.ofNullable(source)
|
||||
.map(List::stream)
|
||||
.orElseGet(Stream::empty)
|
||||
.skip(1)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Car {
|
||||
|
||||
private String model;
|
||||
private int topSpeed;
|
||||
|
||||
public Car(String model, int topSpeed) {
|
||||
super();
|
||||
this.model = model;
|
||||
this.topSpeed = topSpeed;
|
||||
}
|
||||
|
||||
public String getModel() {
|
||||
return model;
|
||||
}
|
||||
|
||||
public void setModel(String model) {
|
||||
this.model = model;
|
||||
}
|
||||
|
||||
public int getTopSpeed() {
|
||||
return topSpeed;
|
||||
}
|
||||
|
||||
public void setTopSpeed(int topSpeed) {
|
||||
this.topSpeed = topSpeed;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.baeldung.java_8_features;
|
||||
|
||||
public class Person {
|
||||
private String name;
|
||||
private Integer age;
|
||||
|
||||
public Person(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Integer getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(Integer age) {
|
||||
this.age = age;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package com.baeldung.findanelement;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
public class FindACustomerInGivenListUnitTest {
|
||||
|
||||
private static List<Customer> customers = new ArrayList<>();
|
||||
|
||||
static {
|
||||
customers.add(new Customer(1, "Jack"));
|
||||
customers.add(new Customer(2, "James"));
|
||||
customers.add(new Customer(3, "Sam"));
|
||||
}
|
||||
|
||||
private static FindACustomerInGivenList findACustomerInGivenList = new FindACustomerInGivenList();
|
||||
|
||||
@Test
|
||||
public void givenAnIndex_whenFoundUsingGivenIndex_thenReturnCustomer() {
|
||||
Customer customer = findACustomerInGivenList.findUsingGivenIndex(0, customers);
|
||||
|
||||
assertEquals(1, customer.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAnIndex_whenNotFoundUsingGivenIndex_thenReturnNull() {
|
||||
Customer customer = findACustomerInGivenList.findUsingGivenIndex(5, customers);
|
||||
|
||||
assertNull(customer);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACustomer_whenFoundUsingContains_thenReturnTrue() {
|
||||
Customer james = new Customer(2, "James");
|
||||
boolean isJamesPresent = findACustomerInGivenList.findUsingContains(james, customers);
|
||||
|
||||
assertEquals(true, isJamesPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACustomer_whenNotFoundUsingContains_thenReturnFalse() {
|
||||
Customer john = new Customer(5, "John");
|
||||
boolean isJohnPresent = findACustomerInGivenList.findUsingContains(john, customers);
|
||||
|
||||
assertEquals(false, isJohnPresent);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACustomer_whenFoundUsingIndexOf_thenReturnItsIndex() {
|
||||
Customer james = new Customer(2, "James");
|
||||
int indexOfJames = findACustomerInGivenList.findUsingIndexOf(james, customers);
|
||||
|
||||
assertEquals(1, indexOfJames);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenACustomer_whenNotFoundUsingIndexOf_thenReturnMinus1() {
|
||||
Customer john = new Customer(5, "John");
|
||||
int indexOfJohn = findACustomerInGivenList.findUsingIndexOf(john, customers);
|
||||
|
||||
assertEquals(-1, indexOfJohn);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingIterator_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingIterator("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingIterator_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingIterator("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingEnhancedFor_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingEnhancedForLoop("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingEnhancedFor_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingEnhancedForLoop("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingStream_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingStream("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingStream_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingStream("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingParallelStream_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingParallelStream("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingParallelStream_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingParallelStream("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingApacheCommon_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingApacheCommon("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingApacheCommon_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingApacheCommon("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameFoundUsingGuava_thenReturnCustomer() {
|
||||
Customer james = findACustomerInGivenList.findUsingGuava("James", customers);
|
||||
|
||||
assertEquals("James", james.getName());
|
||||
assertEquals(2, james.getId());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenName_whenCustomerWithNameNotFoundUsingGuava_thenReturnNull() {
|
||||
Customer john = findACustomerInGivenList.findUsingGuava("John", customers);
|
||||
|
||||
assertNull(john);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
package com.baeldung.hashtable;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
import java.util.Enumeration;
|
||||
import java.util.Hashtable;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import org.junit.Test;
|
||||
|
||||
public class HashtableUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenPutAndGet_thenReturnsValue() {
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
|
||||
Word word = new Word("cat");
|
||||
table.put(word, "an animal");
|
||||
|
||||
String definition = table.get(word);
|
||||
|
||||
assertEquals("an animal", definition);
|
||||
|
||||
definition = table.remove(word);
|
||||
|
||||
assertEquals("an animal", definition);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenThesameInstanceOfKey_thenReturnsValue() {
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
Word word = new Word("cat");
|
||||
table.put(word, "an animal");
|
||||
String extracted = table.get(word);
|
||||
assertEquals("an animal", extracted);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEqualsOverridden_thenReturnsValue() {
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
Word word = new Word("cat");
|
||||
table.put(word, "an animal");
|
||||
String extracted = table.get(new Word("cat"));
|
||||
assertEquals("an animal", extracted);
|
||||
}
|
||||
|
||||
@Test(expected = NullPointerException.class)
|
||||
public void whenNullKey_thenException() {
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(null, "an animal");
|
||||
}
|
||||
|
||||
@Test(expected = ConcurrentModificationException.class)
|
||||
public void whenIterate_thenFailFast() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "an animal");
|
||||
table.put(new Word("dog"), "another animal");
|
||||
|
||||
Iterator<Word> it = table.keySet().iterator();
|
||||
System.out.println("iterator created");
|
||||
|
||||
table.remove(new Word("dog"));
|
||||
System.out.println("element removed");
|
||||
|
||||
while (it.hasNext()) {
|
||||
Word key = it.next();
|
||||
System.out.println(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenEnumerate_thenNotFailFast() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("1"), "one");
|
||||
table.put(new Word("2"), "two");
|
||||
table.put(new Word("3"), "three");
|
||||
table.put(new Word("4"), "four");
|
||||
table.put(new Word("5"), "five");
|
||||
table.put(new Word("6"), "six");
|
||||
table.put(new Word("7"), "seven");
|
||||
table.put(new Word("8"), "eight");
|
||||
|
||||
Enumeration<Word> enumKey = table.keys();
|
||||
System.out.println("Enumeration created");
|
||||
table.remove(new Word("1"));
|
||||
System.out.println("element removed");
|
||||
while (enumKey.hasMoreElements()) {
|
||||
Word key = enumKey.nextElement();
|
||||
System.out.println(table.get(key));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenAddElements_thenIterationOrderUnpredicable() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("1"), "one");
|
||||
table.put(new Word("2"), "two");
|
||||
table.put(new Word("3"), "three");
|
||||
table.put(new Word("4"), "four");
|
||||
table.put(new Word("5"), "five");
|
||||
table.put(new Word("6"), "six");
|
||||
table.put(new Word("7"), "seven");
|
||||
table.put(new Word("8"), "eight");
|
||||
|
||||
Iterator<Map.Entry<Word, String>> it = table.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
Map.Entry<Word, String> entry = it.next();
|
||||
System.out.println(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenGetOrDefault_thenDefaultGot() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
Word key = new Word("dog");
|
||||
String definition;
|
||||
|
||||
// old way
|
||||
/* if (table.containsKey(key)) {
|
||||
definition = table.get(key);
|
||||
} else {
|
||||
definition = "not found";
|
||||
}*/
|
||||
|
||||
// new way
|
||||
definition = table.getOrDefault(key, "not found");
|
||||
|
||||
assertThat(definition, is("not found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenPutifAbsent_thenNotRewritten() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
String definition = "an animal";
|
||||
// old way
|
||||
/* if (!table.containsKey(new Word("cat"))) {
|
||||
table.put(new Word("cat"), definition);
|
||||
}*/
|
||||
// new way
|
||||
table.putIfAbsent(new Word("cat"), definition);
|
||||
|
||||
assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenRemovePair_thenCheckKeyAndValue() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
// old way
|
||||
/* if (table.get(new Word("cat")).equals("an animal")) {
|
||||
table.remove(new Word("cat"));
|
||||
}*/
|
||||
|
||||
// new way
|
||||
boolean result = table.remove(new Word("cat"), "an animal");
|
||||
|
||||
assertThat(result, is(false));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplacePair_thenValueChecked() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
String definition = "an animal";
|
||||
|
||||
// old way
|
||||
/* if (table.containsKey(new Word("cat")) && table.get(new Word("cat")).equals("a small domesticated carnivorous mammal")) {
|
||||
table.put(new Word("cat"), definition);
|
||||
}*/
|
||||
// new way
|
||||
table.replace(new Word("cat"), "a small domesticated carnivorous mammal", definition);
|
||||
|
||||
assertThat(table.get(new Word("cat")), is("an animal"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenKeyIsAbsent_thenNotRewritten() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
// old way
|
||||
/* if (!table.containsKey(cat)) {
|
||||
String definition = "an animal";// calculate
|
||||
table.put(new Word("cat"), definition);
|
||||
}
|
||||
*/
|
||||
// new way
|
||||
|
||||
table.computeIfAbsent(new Word("cat"), key -> "an animal");
|
||||
assertThat(table.get(new Word("cat")), is("a small domesticated carnivorous mammal"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenKeyIsPresent_thenComputeIfPresent() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
|
||||
Word cat = new Word("cat");
|
||||
// old way
|
||||
/* if (table.containsKey(cat)) {
|
||||
String concatination = cat.getName() + " - " + table.get(cat);
|
||||
table.put(cat, concatination);
|
||||
}*/
|
||||
|
||||
// new way
|
||||
table.computeIfPresent(cat, (key, value) -> key.getName() + " - " + value);
|
||||
|
||||
assertThat(table.get(cat), is("cat - a small domesticated carnivorous mammal"));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenCompute_thenForAllKeys() {
|
||||
|
||||
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
|
||||
String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };
|
||||
for (String animal : animals) {
|
||||
table.compute(animal, (key, value) -> (value == null ? 1 : value + 1));
|
||||
}
|
||||
assertThat(table.values(), hasItems(2, 2, 2, 1));
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenInsteadOfCompute_thenMerge() {
|
||||
|
||||
Hashtable<String, Integer> table = new Hashtable<String, Integer>();
|
||||
String[] animals = { "cat", "dog", "dog", "cat", "bird", "mouse", "mouse" };
|
||||
for (String animal : animals) {
|
||||
table.merge(animal, 1, (oldValue, value) -> (oldValue + value));
|
||||
}
|
||||
assertThat(table.values(), hasItems(2, 2, 2, 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenForeach_thenIterate() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
table.put(new Word("dog"), "another animal");
|
||||
table.forEach((k, v) -> System.out.println(k.getName() + " - " + v)
|
||||
|
||||
);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenReplaceall_thenNoIterationNeeded() {
|
||||
|
||||
Hashtable<Word, String> table = new Hashtable<Word, String>();
|
||||
table.put(new Word("cat"), "a small domesticated carnivorous mammal");
|
||||
table.put(new Word("dog"), "another animal");
|
||||
table.replaceAll((k, v) -> k.getName() + " - " + v);
|
||||
|
||||
assertThat(table.values(), hasItems("cat - a small domesticated carnivorous mammal", "dog - another animal"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.baeldung.iterators;
|
||||
|
||||
import static com.baeldung.iterators.Iterators.failFast1;
|
||||
import static com.baeldung.iterators.Iterators.failFast2;
|
||||
import static com.baeldung.iterators.Iterators.failSafe1;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
import java.util.ConcurrentModificationException;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
/**
|
||||
* Source code https://github.com/eugenp/tutorials
|
||||
*
|
||||
* @author Santosh Thakur
|
||||
*/
|
||||
|
||||
public class IteratorsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenFailFast_ThenThrowsException() {
|
||||
assertThatThrownBy(() -> {
|
||||
failFast1();
|
||||
}).isInstanceOf(ConcurrentModificationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFailFast_ThenThrowsExceptionInSecondIteration() {
|
||||
assertThatThrownBy(() -> {
|
||||
failFast2();
|
||||
}).isInstanceOf(ConcurrentModificationException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenFailSafe_ThenDoesNotThrowException() {
|
||||
assertThat(failSafe1()).isGreaterThanOrEqualTo(0);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.baeldung.java.list;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
import static org.junit.Assert.assertFalse;
|
||||
import static org.junit.Assert.assertNotEquals;
|
||||
import static org.junit.Assert.assertNotNull;
|
||||
import static org.junit.Assert.assertTrue;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.Test;
|
||||
|
||||
public class CopyListServiceUnitTest {
|
||||
|
||||
List<Flower> flowers;
|
||||
|
||||
private CopyListService copyListService;
|
||||
|
||||
@Before
|
||||
public void init() {
|
||||
this.copyListService = new CopyListService();
|
||||
this.flowers = new ArrayList<>();
|
||||
|
||||
Flower poppy = new Flower("Poppy", 12);
|
||||
flowers.add(poppy);
|
||||
Flower anemone = new Flower("Anemone", 8);
|
||||
flowers.add(anemone);
|
||||
Flower catmint = new Flower("Catmint", 12);
|
||||
flowers.add(catmint);
|
||||
Flower diascia = new Flower("Diascia", 5);
|
||||
flowers.add(diascia);
|
||||
Flower iris = new Flower("Iris", 3);
|
||||
flowers.add(iris);
|
||||
Flower pansy = new Flower("Pansy", 5);
|
||||
flowers.add(pansy);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByConstructor() {
|
||||
List<Flower> copy = copyListService.copyListByConstructor(flowers);
|
||||
assertEquals(copy.size(), flowers.size());
|
||||
assertTrue(copy.containsAll(flowers));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByConstructor() {
|
||||
List<Flower> copy = copyListService.copyListByConstructorAndEditOneFlowerInTheNewList(flowers);
|
||||
assertEquals(copy.size(), flowers.size());
|
||||
assertTrue(copy.containsAll(flowers));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByAddAllmethod() {
|
||||
List<Flower> copy = copyListService.copyListByAddAllMethod(flowers);
|
||||
assertEquals(copy.size(), flowers.size());
|
||||
assertTrue(copy.containsAll(flowers));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneModifiedElementByAddAllmethod() {
|
||||
List<Flower> copy = copyListService.copyListByAddAllMethodAndEditOneFlowerInTheNewList(flowers);
|
||||
assertEquals(copy.size(), flowers.size());
|
||||
assertTrue(copy.containsAll(flowers));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListsHaveSameSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() {
|
||||
List<Integer> source = Arrays.asList(1,2,3);
|
||||
List<Integer> dest = Arrays.asList(4,5,6);
|
||||
|
||||
dest = copyListService.copyListByCopyMethod(source, dest);
|
||||
assertEquals(dest.size(), source.size());
|
||||
assertTrue(dest.containsAll(source));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListsHaveDifferentSize_thenReturnAnotherListWithTheSameElementsByCopyMethod() {
|
||||
List<Integer> source = Arrays.asList(1,2,3);
|
||||
List<Integer> dest = Arrays.asList(5,6,7,8,9,10);
|
||||
|
||||
dest = copyListService.copyListByCopyMethod(source, dest);
|
||||
assertNotEquals(dest.size(), source.size());
|
||||
assertTrue(dest.containsAll(source));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithTheSameElementsByStreamProcess() {
|
||||
List<Flower> copy = copyListService.copyListByStream(flowers);
|
||||
assertEquals(copy.size(), flowers.size());
|
||||
assertTrue(copy.containsAll(flowers));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithOneElementLessByStreamProcess() {
|
||||
List<Flower> copy = copyListService.copyListByStreamAndSkipFirstElement(flowers);
|
||||
assertNotEquals(copy.size(), flowers.size());
|
||||
assertEquals(copy.size() + 1, flowers.size());
|
||||
assertFalse(copy.containsAll(flowers));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListDoesNotHaveNullElements_thenReturnAnotherListWithFilterElementsByStreamProcess() {
|
||||
List<Flower> copy = copyListService.copyListByStreamWithFilter(flowers, 5);
|
||||
assertNotEquals(copy.size(), flowers.size());
|
||||
assertEquals(copy.size() + 3, flowers.size());
|
||||
assertFalse(copy.containsAll(flowers));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListIsNull_thenReturnEmptyListByStreamProcess() {
|
||||
List<Flower> copy = copyListService.copyListByStreamWithOptional(null);
|
||||
assertNotNull(copy);
|
||||
assertEquals(copy.size(), 0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListIsNotNull_thenReturnAnotherListWithTheElementsByStreamProcess() {
|
||||
List<Flower> copy = copyListService.copyListByStreamWithOptional(flowers);
|
||||
assertEquals(copy.size(), flowers.size());
|
||||
assertTrue(copy.containsAll(flowers));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenAList_whenListIsNotNull_thenReturnAnotherListWithOneElementLessByStreamProcess() {
|
||||
List<Flower> copy = copyListService.copyListByStreamWithOptionalAndSkip(flowers);
|
||||
assertNotEquals(copy.size(), flowers.size());
|
||||
assertEquals(copy.size() + 1, flowers.size());
|
||||
assertFalse(copy.containsAll(flowers));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.baeldung.java8;
|
||||
|
||||
import com.baeldung.java_8_features.Car;
|
||||
import com.baeldung.java_8_features.Person;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
import static org.junit.Assert.assertEquals;
|
||||
|
||||
public class Java8MaxMinUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenListIsOfIntegerThenMaxCanBeDoneUsingIntegerComparator() {
|
||||
//given
|
||||
final List<Integer> listOfIntegers = Arrays.asList(1, 2, 3, 4, 56, 7, 89, 10);
|
||||
final Integer expectedResult = 89;
|
||||
|
||||
//then
|
||||
final Integer max = listOfIntegers
|
||||
.stream()
|
||||
.mapToInt(v -> v)
|
||||
.max().orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals("Should be 89", expectedResult, max);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenListIsOfPersonObjectThenMinCanBeDoneUsingCustomComparatorThroughLambda() {
|
||||
//given
|
||||
final Person alex = new Person("Alex", 23);
|
||||
final Person john = new Person("John", 40);
|
||||
final Person peter = new Person("Peter", 32);
|
||||
final List<Person> people = Arrays.asList(alex, john, peter);
|
||||
|
||||
//then
|
||||
final Person minByAge = people
|
||||
.stream()
|
||||
.min(Comparator.comparing(Person::getAge))
|
||||
.orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals("Should be Alex", alex, minByAge);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIsOfIntegerThenMinUsesIntegerComparator() {
|
||||
int[] integers = new int[] { 20, 98, 12, 7, 35 };
|
||||
|
||||
int min = Arrays.stream(integers)
|
||||
.min()
|
||||
.getAsInt();
|
||||
|
||||
assertEquals(7, min);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenArrayIsOfCustomTypeThenMaxUsesCustomComparator() {
|
||||
final Car porsche = new Car("Porsche 959", 319);
|
||||
final Car ferrari = new Car("Ferrari 288 GTO", 303);
|
||||
final Car bugatti = new Car("Bugatti Veyron 16.4 Super Sport", 415);
|
||||
final Car mcLaren = new Car("McLaren F1", 355);
|
||||
final Car[] fastCars = { porsche, ferrari, bugatti, mcLaren };
|
||||
|
||||
final Car maxBySpeed = Arrays.stream(fastCars)
|
||||
.max(Comparator.comparing(Car::getTopSpeed))
|
||||
.orElseThrow(NoSuchElementException::new);
|
||||
|
||||
assertEquals(bugatti, maxBySpeed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.baeldung.shufflingcollections;
|
||||
|
||||
import org.junit.Test;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
public class ShufflingCollectionsUnitTest {
|
||||
|
||||
@Test
|
||||
public void whenShufflingList_thenListIsShuffled() {
|
||||
List<String> students = Arrays.asList("Foo", "Bar", "Baz", "Qux");
|
||||
|
||||
System.out.println("List before shuffling:");
|
||||
System.out.println(students);
|
||||
|
||||
Collections.shuffle(students);
|
||||
System.out.println("List after shuffling:");
|
||||
System.out.println(students);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingMapEntries_thenValuesAreShuffled() {
|
||||
Map<Integer, String> studentsById = new HashMap<>();
|
||||
studentsById.put(1, "Foo");
|
||||
studentsById.put(2, "Bar");
|
||||
studentsById.put(3, "Baz");
|
||||
studentsById.put(4, "Qux");
|
||||
|
||||
System.out.println("Students before shuffling:");
|
||||
System.out.println(studentsById.values());
|
||||
|
||||
List<Map.Entry<Integer, String>> shuffledStudentEntries = new ArrayList<>(studentsById.entrySet());
|
||||
Collections.shuffle(shuffledStudentEntries);
|
||||
|
||||
List<String> shuffledStudents = shuffledStudentEntries.stream()
|
||||
.map(Map.Entry::getValue)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
System.out.println("Students after shuffling");
|
||||
System.out.println(shuffledStudents);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingSet_thenElementsAreShuffled() {
|
||||
Set<String> students = new HashSet<>(Arrays.asList("Foo", "Bar", "Baz", "Qux"));
|
||||
|
||||
System.out.println("Set before shuffling:");
|
||||
System.out.println(students);
|
||||
|
||||
List<String> studentList = new ArrayList<>(students);
|
||||
|
||||
Collections.shuffle(studentList);
|
||||
System.out.println("Shuffled set elements:");
|
||||
System.out.println(studentList);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void whenShufflingWithSameRandomness_thenElementsAreShuffledDeterministically() {
|
||||
List<String> students_1 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
|
||||
List<String> students_2 = Arrays.asList("Foo", "Bar", "Baz", "Qux");
|
||||
|
||||
Collections.shuffle(students_1, new Random(5));
|
||||
Collections.shuffle(students_2, new Random(5));
|
||||
|
||||
assertThat(students_1).isEqualTo(students_2);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user