This commit is contained in:
Ahmed Tawila
2017-12-04 00:10:44 +02:00
42 changed files with 2625 additions and 760 deletions

View File

@@ -0,0 +1,116 @@
package com.baeldung.array;
import org.junit.Test;
import java.util.*;
public class SearchArrayTest {
@Test
public void searchArrayAllocNewCollections() {
int count = 1000;
String[] strings = seedArray(count);
long startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchList(strings, "W");
}
long duration = System.nanoTime() - startTime;
System.out.println("SearchList: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchSet(strings,"S");
}
duration = System.nanoTime() - startTime;
System.out.println("SearchSet: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchLoop(strings, "T");
}
duration = System.nanoTime() - startTime;
System.out.println("SearchLoop: " + duration / 10000);
}
@Test
public void searchArrayReuseCollections() {
int count = 10000;
String[] strings = seedArray(count);
List<String> asList = Arrays.asList(strings);
Set<String> asSet = new HashSet<>(Arrays.asList(strings));
long startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
asList.contains("W");
}
long duration = System.nanoTime() - startTime;
System.out.println("List: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
asSet.contains("S");
}
duration = System.nanoTime() - startTime;
System.out.println("Set: " + duration / 10000);
startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
searchLoop(strings, "T");
}
duration = System.nanoTime() - startTime;
System.out.println("Loop: " + duration / 10000);
}
@Test
public void searchArrayBinarySearch() {
int count = 10000;
String[] strings = seedArray(count);
Arrays.sort(strings);
long startTime = System.nanoTime();
for (int i = 0; i < count; i++) {
Arrays.binarySearch(strings, "A");
}
long duration = System.nanoTime() - startTime;
System.out.println("Binary search: " + duration / 10000);
}
private boolean searchList(String[] strings, String searchString) {
return Arrays.asList(strings).contains(searchString);
}
private boolean searchSet(String[] strings, String searchString) {
Set<String> set = new HashSet<>(Arrays.asList(strings));
return set.contains(searchString);
}
private boolean searchLoop(String[] strings, String searchString) {
for (String s : strings) {
if (s.equals(searchString))
return true;
}
return false;
}
private String[] seedArray(int length) {
String[] strings = new String[length];
Random random = new Random();
for (int i = 0; i < length; i++)
{
strings[i] = String.valueOf(random.nextInt());
}
return strings;
}
}

View File

@@ -0,0 +1,93 @@
package com.baeldung.collection;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.junit.Assert;
import org.junit.Test;
public class WhenUsingHashSet {
@Test
public void whenAddingElement_shouldAddElement() {
Set<String> hashset = new HashSet<>();
Assert.assertTrue(hashset.add("String Added"));
}
@Test
public void whenCheckingForElement_shouldSearchForElement() {
Set<String> hashsetContains = new HashSet<>();
hashsetContains.add("String Added");
Assert.assertTrue(hashsetContains.contains("String Added"));
}
@Test
public void whenCheckingTheSizeOfHashSet_shouldReturnThesize() {
Set<String> hashSetSize = new HashSet<>();
hashSetSize.add("String Added");
Assert.assertEquals(1, hashSetSize.size());
}
@Test
public void whenCheckingForEmptyHashSet_shouldCheckForEmpty() {
Set<String> emptyHashSet = new HashSet<>();
Assert.assertTrue(emptyHashSet.isEmpty());
}
@Test
public void whenRemovingElement_shouldRemoveElement() {
Set<String> removeFromHashSet = new HashSet<>();
removeFromHashSet.add("String Added");
Assert.assertTrue(removeFromHashSet.remove("String Added"));
}
@Test
public void whenClearingHashSet_shouldClearHashSet() {
Set<String> clearHashSet = new HashSet<>();
clearHashSet.add("String Added");
clearHashSet.clear();
Assert.assertTrue(clearHashSet.isEmpty());
}
@Test
public void whenIteratingHashSet_shouldIterateHashSet() {
Set<String> hashset = new HashSet<>();
hashset.add("First");
hashset.add("Second");
hashset.add("Third");
Iterator<String> itr = hashset.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
@Test(expected = ConcurrentModificationException.class)
public void whenModifyingHashSetWhileIterating_shouldThrowException() {
Set<String> hashset = new HashSet<>();
hashset.add("First");
hashset.add("Second");
hashset.add("Third");
Iterator<String> itr = hashset.iterator();
while (itr.hasNext()) {
itr.next();
hashset.remove("Second");
}
}
@Test
public void whenRemovingElementUsingIterator_shouldRemoveElement() {
Set<String> hashset = new HashSet<>();
hashset.add("First");
hashset.add("Second");
hashset.add("Third");
Iterator<String> itr = hashset.iterator();
while (itr.hasNext()) {
String element = itr.next();
if (element.equals("Second"))
itr.remove();
}
Assert.assertEquals(2, hashset.size());
}
}

View File

@@ -0,0 +1,157 @@
package com.baeldung.jdbcrowset;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.FilteredRowSet;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.JoinRowSet;
import javax.sql.rowset.RowSetFactory;
import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;
import org.junit.Before;
import org.junit.Test;
import com.sun.rowset.CachedRowSetImpl;
import com.sun.rowset.JdbcRowSetImpl;
import com.sun.rowset.JoinRowSetImpl;
import com.sun.rowset.WebRowSetImpl;
public class JdbcRowSetTest {
Statement stmt = null;
String username = "sa";
String password = "";
String url = "jdbc:h2:mem:testdb";
String sql = "SELECT * FROM customers";
@Before
public void setup() throws Exception {
Connection conn = DatabaseConfiguration.geth2Connection();
String drop = "DROP TABLE IF EXISTS customers, associates;";
String schema = "CREATE TABLE customers (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id)); ";
String schemapartb = "CREATE TABLE associates (id INT NOT NULL, name VARCHAR(50) NOT NULL, PRIMARY KEY (id));";
stmt = conn.createStatement();
stmt.executeUpdate(drop);
stmt.executeUpdate(schema);
stmt.executeUpdate(schemapartb);
DatabaseConfiguration.initDatabase(stmt);
}
// JdbcRowSet Example
@Test
public void createJdbcRowSet_SelectCustomers_ThenCorrect() throws Exception {
String sql = "SELECT * FROM customers";
JdbcRowSet jdbcRS;
Connection conn = DatabaseConfiguration.geth2Connection();
jdbcRS = new JdbcRowSetImpl(conn);
jdbcRS.setType(ResultSet.TYPE_SCROLL_INSENSITIVE);
jdbcRS.setCommand(sql);
jdbcRS.execute();
jdbcRS.addRowSetListener(new ExampleListener());
while (jdbcRS.next()) {
// each call to next, generates a cursorMoved event
System.out.println("id=" + jdbcRS.getString(1));
System.out.println("name=" + jdbcRS.getString(2));
}
}
// CachedRowSet Example
@Test
public void createCachedRowSet_DeleteRecord_ThenCorrect() throws Exception {
CachedRowSet crs = new CachedRowSetImpl();
crs.setUsername(username);
crs.setPassword(password);
crs.setUrl(url);
crs.setCommand(sql);
crs.execute();
crs.addRowSetListener(new ExampleListener());
while (crs.next()) {
if (crs.getInt("id") == 1) {
System.out.println("CRS found customer1 and will remove the record.");
crs.deleteRow();
break;
}
}
}
// WebRowSet example
@Test
public void createWebRowSet_SelectCustomers_WritetoXML_ThenCorrect() throws SQLException, IOException {
WebRowSet wrs = new WebRowSetImpl();
wrs.setUsername(username);
wrs.setPassword(password);
wrs.setUrl(url);
wrs.setCommand(sql);
wrs.execute();
FileOutputStream ostream = new FileOutputStream("customers.xml");
wrs.writeXml(ostream);
}
// JoinRowSet example
@Test
public void createCachedRowSets_DoJoinRowSet_ThenCorrect() throws Exception {
CachedRowSetImpl customers = new CachedRowSetImpl();
customers.setUsername(username);
customers.setPassword(password);
customers.setUrl(url);
customers.setCommand(sql);
customers.execute();
CachedRowSetImpl associates = new CachedRowSetImpl();
associates.setUsername(username);
associates.setPassword(password);
associates.setUrl(url);
String associatesSQL = "SELECT * FROM associates";
associates.setCommand(associatesSQL);
associates.execute();
JoinRowSet jrs = new JoinRowSetImpl();
final String ID = "id";
final String NAME = "name";
jrs.addRowSet(customers, ID);
jrs.addRowSet(associates, ID);
jrs.last();
System.out.println("Total rows: " + jrs.getRow());
jrs.beforeFirst();
while (jrs.next()) {
String string1 = jrs.getString(ID);
String string2 = jrs.getString(NAME);
System.out.println("ID: " + string1 + ", NAME: " + string2);
}
}
// FilteredRowSet example
@Test
public void createFilteredRowSet_filterByRegexExpression_thenCorrect() throws Exception {
RowSetFactory rsf = RowSetProvider.newFactory();
FilteredRowSet frs = rsf.createFilteredRowSet();
frs.setCommand("select * from customers");
Connection conn = DatabaseConfiguration.geth2Connection();
frs.execute(conn);
frs.setFilter(new FilterExample("^[A-C].*"));
ResultSetMetaData rsmd = frs.getMetaData();
int columncount = rsmd.getColumnCount();
while (frs.next()) {
for (int i = 1; i <= columncount; i++) {
System.out.println(rsmd.getColumnLabel(i) + " = " + frs.getObject(i) + " ");
}
}
}
}

View File

@@ -1,11 +1,38 @@
package com.baeldung.loops;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class WhenUsingLoops {
private LoopsInJava loops = new LoopsInJava();
private static List<String> list = new ArrayList<>();
private static Set<String> set = new HashSet<>();
private static Map<String, Integer> map = new HashMap<>();
@BeforeClass
public static void setUp() {
list.add("One");
list.add("Two");
list.add("Three");
set.add("Four");
set.add("Five");
set.add("Six");
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
}
@Test
public void shouldRunForLoop() {
@@ -34,4 +61,47 @@ public class WhenUsingLoops {
int[] actual = loops.do_while_loop();
Assert.assertArrayEquals(expected, actual);
}
@Test
public void whenUsingSimpleFor_shouldIterateList() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateList() {
for (String item : list) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateSet() {
for (String item : set) {
System.out.println(item);
}
}
@Test
public void whenUsingEnhancedFor_shouldIterateMap() {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + " - " + "Value: " + entry.getValue());
}
}
@Test
public void whenUsingSimpleFor_shouldRunLabelledLoop() {
aa: for (int i = 1; i <= 3; i++) {
if (i == 1)
continue;
bb: for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break aa;
}
System.out.println(i + " " + j);
}
}
}
}