#Java - Code Snippets for '#Arrays' - 28 code snippet(s) found |
|
Sample 1. Usage of Apache Commons - ArrayListValuedHashMap | |
|
ListValuedMap<String,String> listValuedMap = new ArrayListValuedHashMap();
listValuedMap.put("United States", "Washington");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("Canada", "Ottawa");
listValuedMap.put("South Africa", "Pretoria");
listValuedMap.put("South Africa", "Cape Town");
listValuedMap.put("South Africa", "Bloemfontein");
System.out.println(listValuedMap); // Values being added to the List and allow even duplicates
|
|
Like Feedback apache commons apache commons collections ArrayListValuedHashMap ListValuedMap |
|
|
Sample 2. Write a Program to implement stack using an array | |
|
public class Stack{
static int top = 0;
static Element[] stack = new Element[10];
static class Element {
int body;
Element(int value){
body = value;
}
}
public static void main(String[] args){
push(5);
System.out.println(top);
push(7);
System.out.println(top);
poll();
System.out.println(top);
poll();
System.out.println(top);
}
private static void push(int value){
Element newElement = new Element(value);
top++;
}
private static Element poll(){
Element topElement = stack[top];
top--;
return topElement;
}
}
|
|
Like Feedback stack |
|
|
Sample 3. Get all Permutations of List Elements using Apache Commons PermutationIterator | |
|
List<String> list = new ArrayList();
list.add("Washington");
list.add("Nevada");
list.add("California");
PermutationIterator permIterator = new PermutationIterator((Collection) list);
permIterator.forEachRemaining(System.out::print); // prints [Washington, Nevada, California][Washington, California, Nevada][California, Washington, Nevada][California, Nevada, Washington][Nevada, California, Washington][Nevada, Washington, California]
|
|
Like Feedback Permutations of collection elements Permutations of List elements Apache Commons PermutationIterator Iterator Collections .forEachRemaining System.out::print List ArrayList |
|
|
Sample 4. Sorting an arraylist using Collections.sort | |
|
List<String> myList = new ArrayList<String>();
myList.add("D");
myList.add("A");
myList.add("B");
myList.add("C");
myList.add("E");
System.out.println(myList); // Unsorted
Collections.sort(myList);
System.out.println(myList); // Sorted
|
|
Like Feedback list arraylist collections.sort collections |
|
|
|
Sample 5. Looping through elements of an ArrayList | |
|
public static void main(String[] args){
List list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
for(Integer element: list){
System.out.println(element);
}
}
|
|
Like Feedback arraylist list collections |
|
|
Sample 6. Display Elements of a List using Java 8 Consumer | |
|
List myList = new ArrayList();
myList.add("A");
myList.add("B");
myList.add("C");
myList.forEach(System.out::println);
|
|
Like Feedback Print elements of a list java 8 consumer foreach list arraylist collections |
|
|
Sample 7. Remove templatized arguments from a String | |
|
String removeTemplatizedArgument(String str){
String cleanStr = "";
boolean withinTemplatized=false;
int countBlock = 0;
for(char x: str.toCharArray()){
if(x == '<'){
withinTemplatized = true;
countBlock++;
continue;
} else if(x == '>'){
withinTemplatized = false;
countBlock--;
continue;
} else if(!withinTemplatized && countBlock == 0){
cleanStr = cleanStr + x;
}
}
return cleanStr;
}
|
|
Like Feedback string string trim trim char .toCharArray() |
|
|
Sample 8. ArrayList of Optional Integers | |
|
List<Optional<Integer>> intList = new ArrayList<Optional<Integer>>();
// Add Elements
intList.add(Optional.empty());
intList.add(Optional.of(2));
intList.add(Optional.of(3));
intList.add(Optional.of(4));
|
|
Like Feedback optional java 8 list arraylist list of optional integers arraylist of optional java.util.Optional |
|
|
Sample 9. Initialize list using google guava Lists | |
|
import java.util.List;
import com.google.common.collect.Lists;
class GoogleListsTest{
public static void main(String[] args){
List list = Lists.newArrayList();
}
}
|
|
Like Feedback list google guava Lists Lists.newArrayList com.google.common.collect.Lists |
|
|
|
Sample 10. Copy Array using System.arraycopy | |
|
String[] stringArray = new String[50];
String[] newStringArray = new String[50];
System.arraycopy(stringArray, 0, newStringArray, 0, 50); //arrayCopy(src,srcPosition,destination,destinationPos,length)
|
|
Like Feedback System.arraycopy Copy array arrays array of string |
|
|
Sample 11. Method to invert / reverse Bit Data | |
|
byte[] bitInvertData(byte[] data, int startIndex, int endIndex){
for (int i = startIndex; i < endIndex; i++) {
data[i] = ((byte)(255 - data[(i - startIndex)]));
}
return data;
}
|
|
Like Feedback bit data reverse bit data byte[] byte array |
|
|
Sample 12. Internal Implementation of ArrayList#removeIf | |
|
@Override
public boolean removeIf(Predicate<? super E> filter) {
Objects.requireNonNull(filter);
int removeCount = 0;
final BitSet removeSet = new BitSet(size);
final int expectedModCount = modCount;
final int size = this.size;
for (int i=0; modCount == expectedModCount && i < size; i++) {
@SuppressWarnings("unchecked")
final E element = (E) elementData[i];
if (filter.test(element)) {
removeSet.set(i);
removeCount++;
}
}
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
// shift surviving elements left over the spaces left by removed elements
final boolean anyToRemove = removeCount > 0;
if (anyToRemove) {
final int newSize = size - removeCount;
for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
i = removeSet.nextClearBit(i);
elementData[j] = elementData[i];
}
for (int k=newSize; k < size; k++) {
elementData[k] = null; // Let gc do its work
}
this.size = newSize;
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
|
|
Like Feedback Internal Implementation of ArrayList#removeIf java.util.function.Predicate java.util.Objects java.util.Objects java.util.ConcurrentModificationException.ConcurrentModificationException |
|
|
Sample 13. Usage of Arrays using Apache Commons ArrayUtils | |
|
int array[] = new int[4];
array[0] = 0;
array[1] = 1;
array[2] = 2;
array[3] = 2;
System.out.println(array.length); // Prints 4
System.out.println(ArrayUtils.contains(array, 3)); // Prints false
array = ArrayUtils.add(array, 3); // Add element 3 to the array
System.out.println(array.length); // Prints 5
System.out.println(ArrayUtils.contains(array, 3)); // Prints true
ArrayUtils.lastIndexOf(array, 2); // prints 3
array = ArrayUtils.removeElement(array, 1); // Remove element 1 to the array
System.out.println(array.length); // Prints 4
System.out.println(ArrayUtils.contains(array, 1)); // Prints false
|
|
Like Feedback arrays ArrayUtils Apache Commons ArrayUtils Example ArrayUtils Sample |
|
|
Sample 14. Usage of java.io.ByteArrayInputStream | |
|
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
result = ois.readObject();
|
|
Like Feedback ByteArrayInputStream java.io input stream ObjectInputStream |
|
|
|
Sample 15. Usage of ByteArrayOutputStream | |
|
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(validator);
oos.flush();
oos.close();
} catch (Exception e) {
}
|
|
Like Feedback java.io.ByteArrayOutputStream java.io ObjectOutputStream |
|
|
Sample 16. Code Sample / Example / Snippet of java.sql.Array | |
|
private void dumpColumn(ResultSet resultSet, int i) throws SQLException {
final int t = resultSet.getMetaData().getColumnType(i);
switch (t) {
case Types.ARRAY:
final Array array = resultSet.getArray(i);
writer.print("{");
dump(array.getResultSet(), false);
writer.print("}");
return;
case Types.REAL:
writer.print(resultSet.getString(i));
writer.print("F");
return;
default:
writer.print(resultSet.getString(i));
}
}
|
|
Like Feedback java.sql.Array |
|
|
Sample 17. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream | |
|
private static Pair<SqlLine.Status, String> run(String... args)
throws Throwable {
SqlLine sqlline = new SqlLine();
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream sqllineOutputStream = new PrintStream(os);
sqlline.setOutputStream(sqllineOutputStream);
sqlline.setErrorStream(sqllineOutputStream);
SqlLine.Status status = SqlLine.Status.OK;
Bug.upgrade("[sqlline-35] Make Sqlline.begin public");
return Pair.of(status, os.toString("UTF8"));
}
|
|
Like Feedback java.io.ByteArrayOutputStream |
|
|
Sample 18. Code Sample / Example / Snippet of org.apache.hc.core5.util.ByteArrayBuffer | |
|
public void testConstructor() throws Exception {
final ByteArrayBuffer buffer = new ByteArrayBuffer(16);
Assert.assertEquals(16, buffer.capacity());
Assert.assertEquals(0, buffer.length());
Assert.assertNotNull(buffer.buffer());
Assert.assertEquals(16, buffer.buffer().length);
try {
new ByteArrayBuffer(-1);
Assert.fail("IllegalArgumentException should have been thrown");
} catch (final IllegalArgumentException ex) {
}
}
|
|
Like Feedback org.apache.hc.core5.util.ByteArrayBuffer |
|
|
Sample 19. Write a program / method that takes an array of integer and return the difference between the smallest and largest element ? | |
|
static int diff(int[] x){
int smallest = x[0];
int largest = x[0];
for(int element: x){
if(element < smallest){
smallest = element;
} else if(element > largest){
largest = element;
} else {
continue;
}
}
return largest-smallest;
}
|
|
Like Feedback difference between the smallest and largest element array |
|
|
|
Sample 20. Code Sample / Example / Snippet of com.google.gson.JsonArray | |
|
private void listRepositoryObjects(Workspace workspace, String entityType, HttpServletResponse resp) throws IOException {
List<RepositoryObject> objects = workspace.getRepositoryObjects(entityType);
JsonArray result = new JsonArray();
for (RepositoryObject ro : objects) {
String identity = ro.getDefinition();
if (identity != null) {
result.add(new JsonPrimitive(urlEncode(identity)));
}
}
resp.getWriter().println(m_gson.toJson(result));
}
|
|
Like Feedback com.google.gson.JsonArray |
|
|
Sample 21. Code Sample / Example / Snippet of java.io.ByteArrayOutputStream | |
|
public int compare(ResourceImpl r1, ResourceImpl r2) {
String s1 = getName(r1);
String s2 = getName(r2);
return s1.compareTo(s2);
}
});
Tag tag = doIndex(sorted);
if (repositoryFileName != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
|
Like Feedback java.io.ByteArrayOutputStream |
|
|
Sample 22. Code Sample / Example / Snippet of java.io.ByteArrayInputStream | |
|
protected final void importSingleUser(Repository userRepository, String userName, String password) throws Exception {
ByteArrayInputStream bis = new ByteArrayInputStream((
"<roles>" +
"<user name="" + userName + "">" +
"<properties><username>" + userName + "</username></properties>" +
"<credentials><password type="String">" + password + "</password></credentials>" +
"</user>" +
"</roles>").getBytes());
Assert.assertTrue("Committing test user data failed!", userRepository.commit(bis, userRepository.getRange().getHigh()));
}
|
|
Like Feedback java.io.ByteArrayInputStream |
|
|
Sample 23. Code Sample / Example / Snippet of org.apache.bcel.classfile.ArrayElementValue | |
|
private void assertArrayElementValue(final int nExpectedArrayValues, final AnnotationEntry anno)
{
final ElementValuePair elementValuePair = anno.getElementValuePairs()[0];
assertEquals("value", elementValuePair.getNameString());
final ArrayElementValue ev = (ArrayElementValue) elementValuePair.getValue();
final ElementValue[] eva = ev.getElementValuesArray();
assertEquals(nExpectedArrayValues, eva.length);
}
|
|
Like Feedback org.apache.bcel.classfile.ArrayElementValue |
|
|
Sample 24. Display elements of a List using For loop | |
|
List myList = new ArrayList();
myList.add("A");
myList.add("B");
myList.add("C");
for(String str:myList){ // prints A B C
System.out.println(str);
}
|
|
Like Feedback Print elements of a list for loop arraylist list collections |
|
|
|
Sample 25. Display elements of a List using For Loop and index | |
|
List myList = new ArrayList();
myList.add("A");
myList.add("B");
myList.add("C");
for(int index=0;index < myList.size(); index++){
System.out.println(myList.get(index));
}
|
|
Like Feedback Print elements of a list arraylist list collections for loop |
|
|
Sample 26. Write CSV values to a file using au.com.bytecode.opencsv.CSVWriter | |
|
String[] stringArray1 = new String[5];
String[] stringArray2 = new String[5];
String[] stringArray3 = new String[5];
List listOfStringArrays = new ArrayList();
listOfStringArrays.add(stringArray1);
listOfStringArrays.add(stringArray2);
listOfStringArrays.add(stringArray3);
File file = new File("BuggyBread.txt");
CSVWriter csvWriter = null;
try {
csvWriter = new CSVWriter(new FileWriter(file),CSVWriter.DEFAULT_SEPARATOR);
} catch (Exception ex){
}
csvWriter.writeAll(listOfStringArrays);
|
|
Like Feedback array of Strings csv writer |
|
|
Sample 27. Print duplicate characters in a string / char array without using library | |
|
public class CountDuplicates {
public static void main(String[] args){
char[] alreadyOccured = new char[10];
char[] charArray = {'b','u','g','g','y','b','r','e','a','d'};
for(int countArray=0;countArray<charArray.length;countArray++){
boolean charAlreadyOccured = false;
for(int countAlreadyOccured=0;countAlreadyOccured<alreadyOccured.length;countAlreadyOccured++){
if(charArray[countArray] == alreadyOccured[countAlreadyOccured]){
charAlreadyOccured = true;
break;
}
}
if(charAlreadyOccured){
System.out.println(charArray[countArray]);
} else {
alreadyOccured[countArray] = charArray[countArray];
}
}
}
}
|
|
Like Feedback string char array |
|
|
Sample 28. Write a Program to find two maximum numbers in an array | |
|
public class FindTwoMax {
public static void main(String[] args) {
int myArray[] = { 1, 3, 5, 8, 6, 3 };
int max1 = myArray[0];
int max2 = 0;
for (int count = 0; count < myArray.length; count++) {
if (max2 < myArray[count]) {
max2 = max1;
max1 = myArray[count];
} else if (max2 < myArray[count]) {
max2 = myArray[count];
}
}
System.out.println(max1);
System.out.println(max2);
}
}
|
|
Like Feedback find 2 max in array |
|
|