How to find median value by using java stream API [duplicate] - java

This question already has answers here:
Finding the median value from a List of objects using Java 8
(6 answers)
Closed 4 years ago.
How to find median value by using java stream API :
For example I have the following array int []arr ={0,1,2,4,6,5,3};
Is there a way and what is the best way to find the median value using java Stream API;
int findMedian() {
int []arr ={0,1,2,4,6,5,3};
IntStream.of(arr).sorted() // what I have to do here
return 0;
}
And what do you think if I changed to a parallel stream for the big array, will it be faster or not ? Is sorting will be on parallel?

I suggest you pass the array to findMedian (and since it doesn't access any fields, make it static). Then you could sort it, convert that back to an array and return the element at half the length. Like,
static int findMedian(int[] arr) {
return IntStream.of(arr).sorted().toArray()[arr.length / 2]);
}
or, skip that many elements and limit it to the first result. Like,
return IntStream.of(arr).sorted().skip(arr.length / 2).limit(1);

Related

Computing the nth Fibonacci number using linear recursion [duplicate]

This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 3 years ago.
I have tried binary recursion to find the nth Fibonacci number (or the whole Fibonacci series by using a for loop in main()) but according to Data Structures and Algorithms in Java (6th Edition) by Michael T. Goodrich; it is a terribly inefficient method as it requires an exponential number of calls to the method. An efficient recursion technique is linear recursion given as follows;
/**Returns array containing the pair of Fibonacci numbers, F(n) and F(n-1)*/
public static long[] fibonacciGood(int n) {
if(n<=1) {
long[] answer = {n,0};
return answer;
}else {
long[] temp = fibonacciGood(n-1); //returns {F(n-1), F(n-2)
long[] answer = {temp[0]+temp[1], temp[0]}; //we want {F(n), F(n-1)}
return answer;
}
}
Whenever I run the code it returns a reference as
[J#15db9742
which is not the desired answer. What should I write in main() so that i can have the desired answer?
Try the one below. You can refer the api here.
public static void main(String[] args) {
System.out.println(Arrays.toString(fibonacciGood(4)));
}
You are trying to print out an array to the console, this is causing the memory address of the array to be output. You may want to iterate through the array returned, printing every element to get the desired output.
Here you are printing the array object, so you are getting these results. Internally it calls toString method of the object, which return getClass().getName() + "#" + Integer.toHexString(hashCode());. So you are getting value as [J#15db9742.
You can use convert is directly as below (Working in Java version 5 and above)
System.out.println(Arrays.toString(fibonacciGood(4)));
You can print it by converting it to list as below (in Java 8 or above) (Not Preferable to use streams here, but just for knowledge):
System.out.println(Arrays.stream(fibonacciGood(4)).boxed().collect(Collectors.toList()));

How to find sum with forEach and lambda expression in Java? [duplicate]

This question already has answers here:
Variable used in lambda expression should be final or effectively final
(9 answers)
How to sum a list of integers with java streams?
(12 answers)
Closed 4 years ago.
The following snippet does not compile. How to find the sum using forEach as shown below?
private int Sum(ArrayList<Integer> inputs) {
int sum = 0;
inputs.stream().forEach(x -> sum += x);
return sum;
}
This should do the trick:
private int Sum(ArrayList<Integer> inputs) {
return inputs.stream().mapToInt(Integer::intValue).sum();
}
EDIT :
The problem with using for-each is that it is a terminal operation, which means that it doesn't produce another intermediate stream for us to work on. The better approach would be to use mapToInt which produces an IntStream on which we can easily find the sum.
This answer is just to provide a bit more context as to why your code doesn't work and therefore allowing you to decipher the problem if it were to happen in the future.
It seems like you're a .NET user which makes it completely understandable for one to expect the code you've written to work. As in .NET the equivalent would be:
private int Sum(List<int> inputs) {
int sum = 0;
inputs.ForEach(x => sum += x);
return sum;
}
However, in java variables used in a lambda expression must be final or effectively final, for that reason the statement inputs.stream().forEach(x -> sum += x); will not compile.
Nevertheless, simply because one would expect the aforementioned code to work in C# doesn't necessarily mean it should work in Java as there are different rules.
There are solutions available to find the sum of a set of numbers using the forEach method but it's not the idiomatic approach and so should be avoided unless necessary.
The idiomatic approach is as #Nicholas K has shown.
On another note:
even in .NET the idiomatic approach would be return inputs.Sum();
as opposed to using the ForEach extension method to sum the elements of a given list.
whenever you seem to see yourself use inputs.stream().forEach(...); in java you should instead do inputs.forEach(...) as all lists have a forEach method.
method names in Java should be camelCase as opposed to PascalCasing as in C#.

What is "int..." in Java method's parameter? [duplicate]

This question already has answers here:
What is the ellipsis (...) for in this method signature?
(5 answers)
What do 3 dots next to a parameter type mean in Java?
(9 answers)
Closed 7 years ago.
I came across a method definition:
void doType(int... keyCodes) {
doType(keyCodes, 0, keyCodes.length);
}
void doType(int[] keyCodes, int offset, int length) {
if (length == 0) {
return;
}
robot.keyPress(keyCodes[offset]);
doType(keyCodes, offset + 1, length - 1);
robot.keyRelease(keyCodes[offset]);
}
The "int..." seems to indicate an indeterminate number of integer parameters but the variable is used as an array inside the function. Can someone please explain?
As you already stated correctly this java notation is to make the method accept a variable amount of (in this case) int parameter.
To handle this variable amount of variables you can access it like an array.
This functionality is introduced in java 5.
See also here:
https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html
You are right in deducing that the ellipses indicate that this method is variadic.
When you have a variable number of potential arguments, you need some way to iterate over them - otherwise they aren't very useful in practice. Java and C# happen to have the array indexing syntax. C and C++ happen to have the va_start, va_arg and va_end macros. Different languages may have something else.
The reason why Java has the array syntax specifically is probably because it happens to match the way they are actually implemented: as a simple array parameter replaced at compile time.

How to find index of int array which match specific value [duplicate]

This question already has answers here:
Why is indexOf failing to find the object?
(3 answers)
Closed 9 years ago.
I have
int myArray[]= {12,23,10,22,10};
So i want to get index of 23 from myArray with out iterating any loop (for ,while ...) .
I would do something like Arrays.asList(myArray).indexOf(23)
This is not work for me . I get -1 as output .
This is work with String[]
Like
String myArray[]= {"12","23","10","22","10"};
Arrays.asList(myArray).indexOf("23")
So why this is not working with int[] ? ?
Integer myArray[]= {12,23,10,22,10};
System.out.println(Arrays.asList(myArray).indexOf(23));
will solve the problem
Arrays.asList(myArray).indexOf(23) this search about objects so we have to use object type of int since int is primitive type.
String myArray[]= {"12","23","10","22","10"};
Arrays.asList(myArray).indexOf("23");
In second case this will work because String is object.
When we define a List,We define it as List<String> or List<Integer>. so primitives are not use in List. Then Arrays.asList(myArray).indexOf("23") find index of equivalent Object.
I concur with Ruchira, and also want to point out that the problem has to do with the fact that int is a primitive while String and Integer are actual objects. (note I would have posted this as a comment but can't until 50 reputation ;) )
If you want to convert an array of primitives to a list of boxed primitives, take advantage of Apache Commons . Once you have the list, as shown below, use the API in List to find object by index.
List<Integer> list = Arrays.asList(ArrayUtils.toObject(myArray));
You can consider keeping your array sorted and use binary subdivision to decide an index. Insert and lookup would both be O(log(n)) in this case (instead of O(1) and O(n) respectively).
If you're doing a lot of looking up you might want to use a different data structure such as a hash map, not just for performance but also because it can be easier to write around.

Find duplicates in an array and return the duplicates in a temp array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java Array, Finding Duplicates
arr=[3,4,1,2,1,5,2]
How do i find the duplicates in this array and then return the duplicates in an array?
In the case the result should be result [1,2]
I am programming in Java.
I recommend taking the following steps:
1) Create a HashSeta. The HashSet will contain integers you have read.
2) Iterate through the entire array [0 ... size - 1]. Keep track of what index you are at with an index variable.
3) In each iteration, do a HashSet.contains(arr[index]) operation. If it is true, it is a duplicate. Save this integer somewhere. Add arr[index] to the set.
4) Return the HashSet as the result.
Use nested for loop. take the first element and compare it with all the array. and then send the duplicated ones to a new array by using if/else logic.
I am not giving a code block because it is tagged as homework.

Categories