I have an array, for example
List<Integer> myArray = Arrays.asList(4, 13, 10, 21, 20);
I want to get a count of total even nums in this array, so I used something like this:
int evenCount = (int)myArray.stream().filter(i -> i % 2 == 0).count();
So count should be 3 in this case, but I wanted to have some clean concise code and maybe chain together some more methods to iterate through the same array but up to this count value that I just computed, then calculate the number of odd numbers below this boundary line, something like:
return IntStream.range(0, evenCount-1).filter(i -> i % 2 !=0).count();
Is there a better way to do this in 1 line? I feel like I am redundantly looping 2 times, but could solve the problem in the first loop (iteration)...
Yes, in this case you can
Map<Boolean, Long> result = List.of(4, 13, 10, 21, 20).stream()
.collect(Collectors.partitioningBy(e -> e % 2 == 0, Collectors.counting()));
System.out.println("result = " + result); // result = {false=2, true=3}
I'm currently learning in school but am unable to complete this part of the assignment.
An explanation with the use of for loops would be greatly appreciated.
The numbers should be added to the merged array in an alternating pattern: first from list 1, then from list 2, then list 1 again, etc. If a number in one of the arrays already appears in the merged array, then it should be ignored, and the program should alternate to the other list again. For example, if the first list begins 1 2 3 10, and the second begins 3 4 5 8, then the merged list would begin 1 3 2 4 5 10 8.
Because the number of elements in the merged array is unknown, its size should be set to the maximum possible number of elements it should contain, and after all elements which should form the merged array appear, any remaining unfilled spaces in the array should be 0. The first 0 encountered in the array should signal the end of the “actual” elements of the array, and therefore the 0s at the end of the array should not be printed by your program.
I propose to use a HashSet to remember which number you have already inserted into the array. For each number, you first check if the hash set already contains the number; if not, you add it to both the array and the set. For large inputs, this is much faster than checking the result array for each number. O(n*log(n)) or so (depending on how well the HashSet works for your input) instead of O(n^2).
#bubble
An example using a Set is very simple - however your teacher is asking for
an alternate list:
Integer[] one = new Integer[] {10,2,3,1};
Integer[] two = new Integer[] {3,8,5,4};
List<Integer> li_one = Arrays.asList(one); // First convert the arrays to a list
List<Integer> li_two = Arrays.asList(two);
Set<Integer> set = new HashSet<>();
set.addAll(li_one);
set.addAll(li_two);
System.out.println("The unique list is: " + set);
A HashSet was my first idea too, but the order of storing values depends
one hash values. The ... teacher likes to have alternating values which
I dont like to comment - because it is a really strange request.
Following code prints: merged list is: [1, 3, 2, 4, 5, 10, 8]
int[] one = new int[] {1,2,3,10};
int[] two = new int[] {3,4,5,8};
int one_len = one.length;
int two_len = two.length;
List<Integer> merged = new ArrayList<>();
int oneval,twoval;
for (int i = 0;i < one_len;i++)
{
oneval = one[i];
if (!merged.contains(oneval)) merged.add(oneval);
if (i < two_len)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
if (two_len > one_len)
{
for (int i = one_len; i < two_len;i++)
{
twoval = two[i];
if (!merged.contains(twoval)) merged.add(twoval);
}
}
System .out.println("merged list is: " + merged);
The NavigableSet.lower(E) Javadoc says it returns the greatest element in this set strictly less than the given element, or null if there is no such element. Why is 1 the output here? Shouldn't it be 4?
NavigableSet original = new TreeSet();
original.add("1");
original.add("2");
original.add("3");
original.add("4");
original.add("10");
Object lower = original.lower("10");
System.out.println(lower);
Because the values are String(s) the Set is comparing by lexical order. Please, don't use Raw Types.
NavigableSet<Integer> original = new TreeSet<>();
original.add(1);
original.add(2);
original.add(3);
original.add(4);
original.add(10);
Object lower = original.lower(10);
System.out.println(lower);
Output is
4
thats because you are comparing Strings here, and not as assumed integers. So the actual order in the Set is : 1, 10, 2, 3, 4 !
Use the generics : NavigableSet<Integer> original = new TreeSet<>(); and add the values as integers :
original.add(1); and so on.
My sample Mongo doc is:
{
"_id" : ObjectId("51fa3d516bde1ca6f017a570"),
"digits":[
0,
1,
2,
3,
4,
5,
6
]
}
I want to append digits array with some extra values.
say:
int[] myIntArray = new int[3];
int[] myIntArray = {7,8,9};
How to append myIntArray to digits array in java
my java code is:
BasicDBList digits=(BasicDBList) cursor.next().get("digits");
MongoDB has the $push operator for that. You don't have to iterate over the collection to do it, you can do an update inside the database.
Written in Java, this would look something like
collection.update(...query expression...,
new BasicDBObject("$push",
new BasicDBObject("digits", value)));
This assumes that value is a single new value for the array. If you want to append all the elements of an array at once, you have to use the $each modifier (see above link for the details).
In C/C++ I used to do
int arr[10] = {0};
...to initialize all my array elements to 0.
Is there a similar shortcut in Java?
I want to avoid using the loop, is it possible?
int arr[] = new int[10];
for(int i = 0; i < arr.length; i++) {
arr[i] = 0;
}
A default value of 0 for arrays of integral types is guaranteed by the language spec:
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type int, the default value is zero, that is, 0.
If you want to initialize an one-dimensional array to a different value, you can use java.util.Arrays.fill() (which will of course use a loop internally).
While the other answers are correct (int array values are by default initialized to 0), if you wanted to explicitly do so (say for example if you wanted an array filled with the value 42), you can use the fill() method of the Arrays class:
int [] myarray = new int[num_elts];
Arrays.fill(myarray, 42);
Or if you're a fan of 1-liners, you can use the Collections.nCopies() routine:
Integer[] arr = Collections.nCopies(3, 42).toArray(new Integer[0]);
Would give arr the value:
[42, 42, 42]
(though it's Integer, and not int, if you need the primitive type you could defer to the Apache Commons ArrayUtils.toPrimitive() routine:
int [] primarr = ArrayUtils.toPrimitive(arr);
In java all elements(primitive integer types byte short, int, long) are initialised to 0 by default. You can save the loop.
How it Reduces the Performance of your application....? Read Following.
In Java Language Specification the Default / Initial Value for any Object can be given as Follows.
For type byte, the default value is zero, that is, the value of (byte) is 0.
For type short, the default value is zero, that is, the value of (short) is 0.
For type int, the default value is zero, that is, 0.
For type long, the default value is zero, that is, 0L.
For type float, the default value is positive zero, that is, 0.0f.
For type double, the default value is positive zero, that is, 0.0d.
For type char, the default value is the null character, that is, '\u0000'.
For type boolean, the default value is false.
For all reference types, the default value is null.
By Considering all this you don't need to initialize with zero values for the array elements because by default all array elements are 0 for int array.
Because An array is a container object that holds a fixed number of values of a single type.
Now the Type of array for you is int so consider the default value for all array elements will be automatically 0 Because it is holding int type.
Now consider the array for String type so that all array elements has default value is null.
Why don't do that......?
you can assign null value by using loop as you suggest in your Question.
int arr[] = new int[10];
for(int i=0;i<arr.length;i++)
arr[i] = 0;
But if you do so then it will an useless loss of machine cycle.
and if you use in your application where you have many arrays and you do that for each array then it will affect the Application Performance up-to considerable level.
The more use of machine cycle ==> More time to Process the data ==> Output time will be significantly increase. so that your application data processing can be considered as a low level(Slow up-to some Level).
You can save the loop, initialization is already made to 0. Even for a local variable.
But please correct the place where you place the brackets, for readability (recognized best-practice):
int[] arr = new int[10];
If you are using Float or Integer then you can assign default value like this ...
Integer[] data = new Integer[20];
Arrays.fill(data,new Integer(0));
You can create a new empty array with your existing array size, and you can assign back them to your array. This may faster than other.
Snipet:
package com.array.zero;
public class ArrayZero {
public static void main(String[] args) {
// Your array with data
int[] yourArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
//Creating same sized array with 0
int[] tempArray = new int[yourArray.length];
Assigning temp array to replace values by zero [0]
yourArray = tempArray;
//testing the array size and value to be zero
for (int item : yourArray) {
System.out.println(item);
}
}
}
Result :
0
0
0
0
0
0
0
0
0
Initialization is not require in case of zero because default value of int in Java is zero.
For values other than zero java.util.Arrays provides a number of options, simplest one is fill method.
int[] arr = new int[5];
Arrays.fill(arr, -1);
System.out.println(Arrays.toString(arr)); //[-1, -1, -1, -1, -1 ]
int [] arr = new int[5];
// fill value 1 from index 0, inclusive, to index 3, exclusive
Arrays.fill(arr, 0, 3, -1 )
System.out.println(Arrays.toString(arr)); // [-1, -1, -1, 0, 0]
We can also use Arrays.setAll() if we want to fill value on condition basis:
int[] array = new int[20];
Arrays.setAll(array, p -> p > 10 ? -1 : p);
int[] arr = new int[5];
Arrays.setAll(arr, i -> i);
System.out.println(Arrays.toString(arr)); // [0, 1, 2, 3, 4]
The int values are already zero after initialization, as everyone has mentioned. If you have a situation where you actually do need to set array values to zero and want to optimize that, use System.arraycopy:
static private int[] zeros = new float[64];
...
int[] values = ...
if (zeros.length < values.length) zeros = new int[values.length];
System.arraycopy(zeros, 0, values, 0, values.length);
This uses memcpy under the covers in most or all JRE implementations. Note the use of a static like this is safe even with multiple threads, since the worst case is multiple threads reallocate zeros concurrently, which doesn't hurt anything.
You could also use Arrays.fill as some others have mentioned. Arrays.fill could use memcpy in a smart JVM, but is probably just a Java loop and the bounds checking that entails.
Benchmark your optimizations, of course.
In c/cpp there is no shortcut but to initialize all the arrays with the zero subscript.Ex:
int arr[10] = {0};
But in java there is a magic tool called Arrays.fill() which will fill all the values in an array with the integer of your choice.Ex:
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
int ar[] = {2, 2, 1, 8, 3, 2, 2, 4, 2};
Arrays.fill(ar, 10);
System.out.println("Array completely filled" +
" with 10\n" + Arrays.toString(ar));
}
}
You defined it correctly in your question, it is nearly the same as for C++. All you need to do for the primitive data type is to initialize the array. Default values are for int 0.
int[] intArray = new int[10];
you can simply do the following
int[] arrayOfZeros= new int[SizeVar];
declare the array as instance variable in the class i.e. out of every method and JVM will give it 0 as default value. You need not to worry anymore
Yes, int values in an array are initialized to zero. But you are not guaranteed this. Oracle documentation states that this is a bad coding practice.
Yet another approach by using lambda above java 8
Arrays.stream(new Integer[nodelist.size()]).map(e ->
Integer.MAX_VALUE).toArray(Integer[]::new);
int a=7, b=7 ,c=0,d=0;
int dizi[][]=new int[a][b];
for(int i=0;i<a;i++){
for(int q=d;q<b;q++){
dizi[i][q]=c;
System.out.print(dizi[i][q]);
c++;
}
c-=b+1;
System.out.println();
}
result
0123456
-1012345
-2-101234
-3-2-10123
-4-3-2-1012
-5-4-3-2-101
-6-5-4-3-2-10