Extracting certain values from an array and putting them in another array - java

I am new to programming so I'm sorry if this is to "noobish" a question.
I have an array containing values which describe the frequency of occurrences - e.g. {4,5,2,7,8,,15,16,12,4,2,7,6,22}. How do I extract the values that are higher than 6 and present them in a new array?

ArrayList<Integer> newList = new ArrayList<Integer>();
for (Integer i: array) {
if (i > 6) {
newList.add(i);
}
}
Integer[] newArray = newList.toArray(new Integer[0]);
Hope this helps.

int j=0;
for(i=0;i<array.length;i++)
{
if(array[i]>6)
{
newArray[j]=array[i];
j++;
}
this is the way you can do it or you can proceed.

Related

HashSet not returning expected output

I want to store unique lists, so I am using HashSet. But, I am not getting desired output. Here is my code, Could you tell me what is going wrong?
public List<List<Integer>> threeSum(int[] nums) {
Set<List<Integer>> res = new HashSet<>();
for(int i = 0; i< nums.length; i++){
int target = 0-nums[i];
Set<Integer> neg = new HashSet<>();
for(int j = i+1 ; j<nums.length; j++){
int rem = target - nums[j];
if(neg.contains(nums[j])){
res.add(new ArrayList<>(Arrays.asList(nums[i], rem, nums[j])));
}
else{
neg.add(rem);
}
}
}
System.out.println(res);
return new ArrayList<>(res);
}
Here my nums is [-1,0,1,2,-1,-4].
My output is [[-1,2,-1],[0,1,-1],[-1,0,1]]. Why am I getting both [0,1,-1] and [-1,0,1] into res as both contain the same elements. I what only one of these? What should I do?
From the Javadoc of List.equals:
Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal.
So, [0,1,-1] and [-1,0,1] aren't equal, despite containing the same elements, because they aren't in the same order.
The easiest way to solve this would be to sort the list:
res.add(Stream.of(nums[i], rem, nums[j]).sorted().collect(toList()));
You can sort the List before adding to the Set so they will be in the same order.

Reverse Array (HackerRank) [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 3 years ago.
Am I leaning in the right direction with my code? I'm currently working on hacker rank and am on the easy section of data structures yet I still am confused about how to reverse this array!
Out of all my attempts, I like these two that I did. Check it out.
one attempt:
two attempts:
You can reverse array in two ways
Either by fetching elements from last to start index and putting elements into new array
for example
int[] b = new int[n];
for(int i = n-1; i>=0 ; i--){
n[i] = arrayTobeReverse[i];
}
for more you can visit : https://www.geeksforgeeks.org/reverse-an-array-in-java/
By using Collection.reverse() method first you have to convert array into List using Arrays.asList(array) you can create List using array and then reverse the List.
for example :
import java.util.*;
public class ReverseDemo
{
public static void main(String[] args)
{
// Let us create a list of strings
List<String> mylist = new ArrayList<String>();
mylist.add("practice");
mylist.add("code");
mylist.add("quiz");
mylist.add("geeksforgeeks");
System.out.println("Original List : " + mylist);
// Here we are using reverse() method
// to reverse the element order of mylist
Collections.reverse(mylist);
System.out.println("Modified List: " + mylist);
}
}
You should be walking down the input array, then populating the target array in the opposite direction:
public static int[] reverseArray(int[] a) {
int[] b = new int[a.length];
for (int i=0; i < a.length; ++i) {
b[i] = a[a.length-i-1];
}
return b;
}
Just for fun, here is way to reverse the order of an original array, without using any extra storage:
// give input int[] a
for (int i=0; i < a.length / 2; ++i) {
a[i] = a[a.length-i-1];
}
Note that this approach just walks down half of the array, and swaps elements about the median.

Array or ArrayList?

Here is an exercise:
Write an algorithm that declares and fills an array of 7 values numerics, bij putting the values to 0.
In Python I have to do this:
note = []
for i in range(7):
note.append(0)
print( note )
I have tried below in Java... I am obliged to use an arrayList?
I would like the do with an array empty.
int[] notes;
for(int i=0;i<7;i++){
notes.add(0);
}
try this:
int[] notes = new int[7];
for(int i=0;i<7;i++){
notes[i] = 0;
}
When declaring your notes array you must initialize it and specify the length of it. If not it will throw a compilation error. Proceed as follows:
int[] notes = new int[7]; //Declare the size of the array as 7
for(int i=0;i<7;i++){
notes[i] = 0; //Iterate the positions of the array via the variable i.
}
If you want to use an ArrayList:
List<Integer> notes = new ArrayList<Integer>(); //You don't have to define the length.
for(int i = 0; i < 7, i++) {
notes.add(0);
}
You can also do like this.
Arrays.fill(notes, -1);// But notes has to be declared.
or
int[] notes = {0,0,0};
For the special case of int and a desired value of 0, you don't even have to write out the loop assignment. You just need this:
int[] notes = new int[7];
This will create an array of ints, each with the Java default value of 0.
You need to use an assignment operation.
notes[i] = 0;
Another option - using streams:
int[] notes = IntStream.range(0, 7).map(i -> 0).toArray();
But if you need exactly 0, you can simply do it like:
int[] notes = new int[7]; // but it for 0 only

Removing Integer from Arraylist

I'm trying to rid of duplicates for my Bingo Program so I created an ArrayList and I want to remove the integer that is printed out in the loop. I think the loop I'm using is wrong but I'm not sure.
List<Integer> list = new ArrayList<Integer>();
for(int i = 1; i <= 75; i++){
list.add(i);
}
for (Integer s : list) {
Collections.shuffle(list);
System.out.println(s);
list.remove(//);
}
Do like this.
for (Iterator<Integer> iterator = list.iterator(); iterator.hasNext();) {
Integer s = iterator.next();
System.out.println(s);
iterator.remove();
}
If you're removing all the integers, it would be a lot easier to just do this:
Collections.shuffle(list);
for (Integer s : list) {
System.out.println(s);
}
list = new ArrayList<Integer>();
Or, if you really want to keep the same list instance:
Collections.shuffle(list);
for (Integer s : list) {
System.out.println(s);
}
list.clear();
Just creating a new array list is more efficient because it allows the garbage collector to just collect the entire old list, rather than removing the entries one by one. If you have multiple references to the same instance, however, then you'd need to actually clear the list instead.
Also note that the shuffle call has been moved outside the loop. Once you've done one shuffle, the list is already randomized, so shuffling again is kind of pointless... If you really want a "better" shuffle, you could do something like call shuffle 7 times before the first loop.
I would suggest using a HashSet<Integer> which doesn't allow duplicates:
Set<Integer> set = new HashSet<Integer>();
Are you sure this is not what you need?
private static final int NUM_BALLS = 75;
List<Integer> list = new ArrayList<Integer>();
for(int i = 1; i <= NUM_BALLS; i++){
list.add(i);
}
Collections.shuffle(list);
while (!list.isEmpty()) {
Integer s = list.remove(list.size() - 1); // for better performance as noted by #Holger
System.out.println(s);
}
use following code
Random generate = new Random();
Set<Integer> set = new HashSet<Integer>();
for(int i = 1; i <= 75; i++){
set.add(generate.nextInt(75));
}
Iterator<Integer> iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
iterator.remove();
}
System.out.print(set.size());

ArrayList of int array in java

I'm new to the concept of arraylist. I've made a short program that is as follows:
ArrayList<int[]> arl=new ArrayList<int[]>();
int a1[]={1,2,3};
arl.add(0,a1);
System.out.println("Arraylist contains:"+arl.get(0));
It gives the output: Arraylist contains:[I#3e25a5
Now my questions are:
How to display the correct value i.e. 1 2 3.
How can I access the single element of array a1 i.e. if I want to know the value at a1[1].
First of all, for initializing a container you cannot use a primitive type (i.e. int; you can use int[] but as you want just an array of integers, I see no use in that). Instead, you should use Integer, as follows:
ArrayList<Integer> arl = new ArrayList<Integer>();
For adding elements, just use the add function:
arl.add(1);
arl.add(22);
arl.add(-2);
Last, but not least, for printing the ArrayList you may use the build-in functionality of toString():
System.out.println("Arraylist contains: " + arl.toString());
If you want to access the i element, where i is an index from 0 to the length of the array-1, you can do a :
int i = 0; // Index 0 is of the first element
System.out.println("The first element is: " + arl.get(i));
I suggest reading first on Java Containers, before starting to work with them.
More simple than that.
List<Integer> arrayIntegers = new ArrayList<>(Arrays.asList(1,2,3));
arrayIntegers.get(1);
In the first line you create the object and in the constructor you pass an array parameter to List.
In the second line you have all the methods of the List class: .get (...)
Use Arrays.toString( arl.get(0) ).
arl.get(0)[1]
The setup:
List<int[]> intArrays=new ArrayList<>();
int anExample[]={1,2,3};
intArrays.add(anExample);
To retrieve a single int[] array in the ArrayList by index:
int[] anIntArray = intArrays.get(0); //'0' is the index
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray ) {
System.out.println("Arraylist contains:" + aNumber );
}
To retrieve all int[] arrays in the ArrayList:
//iterate the ArrayList, get and print the elements of each int[] array
for(int[] anIntArray:intArrays) {
//iterate the retrieved array an print the individual elements
for (int aNumber : anIntArray) {
System.out.println("Arraylist contains:" + aNumber);
}
}
Output formatting can be performed based on this logic. Goodluck!!
In java, an array is an object. Therefore the call to arl.get(0) returns a primitive int[] object which appears as ascii in your call to System.out.
The answer to your first question is therefore
System.out.println("Arraylist contains:"+Arrays.toString( arl.get( 0 ) ) );
If you're looking for particular elements, the returned int[] object must be referenced as such.
The answer to your second question would be something like
int[] contentFromList = arl.get(0);
for (int i = 0; i < contentFromList.length; i++) {
int j = contentFromList[i];
System.out.println("Value at index - "+i+" is :"+j);
}
You have to use <Integer> instead of <int>:
int a1[] = {1,2,3};
ArrayList<Integer> arl=new ArrayList<Integer>();
for(int i : a1) {
arl.add(i);
System.out.println("Arraylist contains:" + arl.get(0));
}
Everyone is right. You can't print an int[] object out directly, but there's also no need to not use an ArrayList of integer arrays.
Using,
Arrays.toString(arl.get(0))
means splitting the String object into a substring if you want to insert anything in between, such as commas.
Here's what I think amv was looking for from an int array viewpoint.
System.out.println("Arraylist contains: "
+ arl.get(0)[0] + ", "
+ arl.get(0)[1] + ", "
+ arl.get(0)[2]);
This answer is a little late for amv but still may be useful to others.
For the more inexperienced, I have decided to add an example to demonstrate how to input and output an ArrayList of Integer arrays based on this question here.
ArrayList<Integer[]> arrayList = new ArrayList<Integer[]>();
while(n > 0)
{
int d = scan.nextInt();
Integer temp[] = new Integer[d];
for (int i = 0 ; i < d ; i++)
{
int t = scan.nextInt();
temp[i]=Integer.valueOf(t);
}
arrayList.add(temp);
n--;
}//n is the size of the ArrayList that has been taken as a user input & d is the size
//of each individual array.
//to print something out from this ArrayList, we take in two
// values,index and index1 which is the number of the line we want and
// and the position of the element within that line (since the question
// followed a 1-based numbering scheme, I did not change it here)
System.out.println(Integer.valueOf(arrayList.get(index-1)[index1-1]));
Thanks to this answer on this question here, I got the correct answer. I believe this satisfactorily answers OP's question, albeit a little late and can serve as an explanation for those with less experience.
java.util.Arrays.toString() converts Java arrays to a string:
System.out.println("Arraylist contains:"+Arrays.toString(arl.get(0)));
ArrayList<Integer> list = new ArrayList<>();
int number, total = 0;
for(int i = 0; i <= list.size(); i++){
System.out.println("Enter number " + (i + 1) + " or enter -1 to end: ");
number = input.nextInt();
list.add(number);
if(number == -1){
list.remove(list.size() - 1);
break;
}
}
System.out.println(list.toString());
for(int i: list){
System.out.print(i + " ");
total+= i;
}
System.out.println();
System.out.println("The sum of the array content is: " + total);
Integer is wrapper class and int is primitive data type.Always prefer using Integer in ArrayList.
List<Integer> integerList = IntStream.range(0,100)
.boxed()
.toList();
This is one of the ways, you can initialize the fixed size ArrayList in Java using Java8+ - Stream API. integerList is going to contain integer values from 0 to 99.

Categories