How to remove duplicate Integer elements in array data structure in java - java

Is there any simple way to remove duplicate elements in Java(will two loops work and how). Thank you:)
IN: int[] arr = {1,3,4,2,3,1,6,7,7};
Output i want is:
{1,3,4,2,6,7}
the only i know is we can traverse it through loop.
eg.
for(int i = 0;i < arr.length;i++){
for(int j = 0;j<arr.length;j++){
if( ){
//what logic i can apply here.
}
}
}

This should work..
final Integer[] noDuplicates =
new LinkedHashSet<>(Arrays.asList(arr)).toArray(new Integer[0]);

Java 8 provides a nice way to do this using IntStream.
arr = Arrays.stream(arr) // Convert arr to IntStream
.distinct() // Get distinct elements (preserves order)
.toArray(); // Convert back to array

You can try this way:
int[]arr = {1,3,4,2,3,1,6,7,7};
Set <Integer> set = new HashSet<Integer>();
for ( int w: arr) {
set.add(w);
}

i think this would be helpful
public static int[] removeduplicate(int a[])
{
int count=0;
for(int i=0;i<a.length;i++)
{
for(int j=i+1;j<a.length;j++)
{
if(a[i]==a[j])
{
a[j]=-1;
count++;
}
}
}
int b[]=new int[a.length-count];
for(int i=0;i<a.length;i++)
{
if(a[i]!=-1)
{
for(int j=0;j<(a.length-count);j++)
{
b[j]=a[i];
}
}
}
return b;
}

You can use set data structure for removing duplicate elements from an array.
int arr[] = {1, 6, 4, 7, 8, 4, 7, 9, 3, 8};
Set<Integer> uniqueNumber = new HashSet<>();
for(int i = 0; i < arr.length; i++) {
//It only contains unique element
uniqueNumber.add(arr[i]);
}
For reference you can check this video tutorial https://www.youtube.com/watch?v=0HBIMjwte7s. I find it very helpful.

First u cant change the existing array , so need a new array to hold his unique numbers, again as you dont know the number of element in advance better to use ArrayList rather array. If you dont want to write to much logic or less number of loops , u can try this.
int[] arr = {1,3,4,2,3,1,6,7,7};
HashSet<Integer> hs = new HashSet<Integer>();
ArrayList<Integer> unique=new ArrayList<Integer>();
for(int num:arr){
if(hs.add(num)){
unique.add(num);
}
}

Related

Split an array into two arrays

I need elements of matrix put into an array, then i need to sort first odd numbers and then even numbers
Example: This is array: 5, 9, 1, 2, 3, 8, 4. output: 1,3,5,9 ; 2,4,8
This is my code:
int[] array=new int[mat.length*mat[0].length];
int cnt=0;
for(int i=0; i<mat.length; i++)
{
for(int j=0; j<mat[0].length; j++)
{
array[cnt]=mat[i][j];
cnt++;
}
}
int cnt1=0;
int cnt2=0;
int[] array1=new int[array.length];
int[] array2=new int[array.length];
for(int i=0; i<array.length; i++)
{
if(array[i]%2==0)
{
array1[br1]=array[i];
cnt1++;
}
else
{
array2[br2]=array[i];
cnt2++;
}
}
The problem is this two arrays for odd and even numbers, because i don't know their length and if i put the size of whole array, then i will get zeros for remaining places in odd array for number that is even and vice versa.
How would you do this?
Thank you
If you can use List you can do
List<Integer> even = new ArrayList<>();
List<Integer> odd = new ArrayList<>();
for(int i=0; i<mat.length; i++) {
for(int j=0; j<mat[0].length; j++) {
if (mat[i][j] % 2 == 0)
even.add(mat[i][j]);
else
odd.add(mat[i][j]);
}
}
Collections.sort(even);
Collections.sort(odd);
odd.addAll(even);
for (int v: odd){
System.out.println(v);
}
Here are a couple of Java 8 solutions (which are far more straightforward):
With two passes of the stream, it's filter and sort.
final int[] ints = {5, 9, 1, 2, 3, 8, 4};
int[] oddArray = Arrays.stream(ints).filter(x -> x % 2 != 0).sorted().toArray();
int[] evenArray = Arrays.stream(ints).filter(x -> x % 2 == 0).sorted().toArray();
System.out.println(Arrays.toString(oddArray));
System.out.println(Arrays.toString(evenArray));
With one pass of the stream, you'd want to use collections so that you don't have to deal with proper sizing of the array. You still have to sort it, though.
final int[] ints = {5, 9, 1, 2, 3, 8, 4};
List<Integer> oddList = new ArrayList<>();
List<Integer> evenList = new ArrayList<>();
Arrays.stream(ints).forEach(e -> {
if(e % 2 != 0) {
oddList.add(e);
} else {
evenList.add(e);
}
});
Collections.sort(oddList);
Collections.sort(evenList);
System.out.println(oddList);
System.out.println(evenList);
There is not problem with array size as there is enough space in each array (array1 and array2) to hold all the numbers and you know the count (cnt1 and cnt2) of elements in each array. Thus after loop you can copy only valid elements to a new array as below:
int[] even = Arrays.copyOf(array1, cnt1);
int[] odd = Arrays.copyOf(array2, cnt2);
Arrays.copyof(..) reference
// This is how you instantiate collections.
List odds = new ArrayList();
List evens = new ArrayList();
...
if(array[i]%2==0)
{
// Here you add a new item to the collection for even numbers
evens.add(array[i];
}
else
{
// Here you add a new item to the collection for odd numbers
odds.add(array[i]);
}
...
// And finally this is how you get arrays out of collections
int[] oddArray = odds.toArray(new int[]);
int[] evenArray = evens.toArray(new int[]);
Thank you all
member #fresidue remind me to this which help me to solve this problem
int cnt=0;
int cnt1=0;
int cnt2=0;
for(int i=0; i<mat.length; i++)
{
for(int j=0; j<mat[0].length; j++)
{
array[cnt]=mat[i][j];
cnt++;
if(mat[i][j]%2==0)
cnt1++;
else
cnt2++;
}
}
int[] array1=new int[cnt1];
int[] array2=new int[cnt2];
You could also use an ArrayList, this has a dynamic size but is a bit slower.
This solves the problem of the zeros

return duplicates from an array in efficient way in java [duplicate]

This question already has answers here:
Java Array, Finding Duplicates
(17 answers)
Closed 8 years ago.
I want to return duplicates in an array.
int[] strArray = new int[] {1,1, 2, 3, 2, 2, 3};
I have used below method to return duplicates.
private static Set<Integer> checkDuplicate(int[] intArray) {
Set<Integer> values = new HashSet<>();
for (int i = 0; i < intArray.length - 1; i++) {
if (intArray[i] == (intArray[i + 1])) {
values.add(intArray[i]);
}
else
System.out.println("not equal");
}
return values;
}
But in this way it checks only the consequtive values.And this needs huge comparisons and time consuming. So is there any better way to do this?
If you do not want to use hashing (HashSet or HashMap), you can first sort the array. And then, you can find duplicates by checking consecutive values. Overall, this method has O(n log n) time complexity.
You may try this example:
import java.util.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int[] strArray = new int[] {1,1, 2, 3, 2, 2, 3, 4, 7, 5, 4};
Set<Integer> duplicates = checkDuplicate(strArray);
System.out.printf("Duplicates: %s\n", duplicates);
}
private static Set<Integer> checkDuplicate(int[] intArray)
{
Set<Integer> duplicates = new HashSet<Integer>();
Set<Integer> tmp = new HashSet<Integer>();
for(Integer i: intArray)
{
if(!tmp.add(i))
{
duplicates.add(i);
}
}
return duplicates;
}
}
If efficiency is what you are looking for then
use HashMap that it has O(1) speed, Also iterate the array of integers in enhanced forloop because it is slightly faster than ordinary forloop
private static Set<Integer> checkDuplicate(int[] intArray) {
HashMap<Integer,Integer> values = new HashMap<Integer,Integer>();
Set<Integer> values2 = new HashSet<Integer>();
for(Integer i : intArray) //0(n)
{
if(values.get(i) != null) //O(1)
values2.add(i);
else
values.put(i, i);
}
return values2;
}
Scan your input and store each number with it's count in a Map<Interger, Integer>. Then loop over the Map and put all keys with value>1 in the resulting Set
See also here: https://stackoverflow.com/a/15217535/461499
You must have to use Collections.frequency
It uses only equals method. If you use any collection Map,Set,List which uses equals method to compare two objects as well as Has collection uses hashCode methods which takes more processing time.
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 1, 4, 4, 1, 5 };
// System.out.println(Arrays.toString(arr));
List<Integer> l = new ArrayList<Integer>();
for (int i = 0; i < arr.length; i++) {
l.add(i, arr[i]);
}
// System.out.println(l);
Set<Integer> set = new HashSet<Integer>();
for (int j = 0; j < l.size(); j++) {
if (Collections.frequency(l, l.get(j)) > 1) {
set.add(l.get(j));
}
}
System.out.println(set);
}
O/P :
[1, 4]

Removing specific value from array (java)

i have integer a = 4 and array b 7,8,9,4,3,4,4,2,1
i have to write a method that removes int ALL a from array b
desired result 7,8,9,3,2,1
This is what I have so far,
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
boolean[] barray = new boolean [array3.length];
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
int[] array4 = new int [array3.length - counter];
int num = 0;
for (int j=0; j<array3.length; j++)
{
if(barray[j] == false)
{
array4[num] = array3[j];
num++;
}
}
return array4;
I get this error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Utility.removeTwo(Utility.java:50)
at Utility.main(Utility.java:18)
Java Result: 1
Any help would be much appreciated!
The error stems from this for loop:
for (int k=0; k<array3.length; k++)
{
barray[k] = (x == array3[k]);
counter++;
}
when you create int[] array4 = new int [array3.length - counter]; you are creating an array with size 0. You should only increment the counter if the item is the desired item to remove:
for (int k=0; k<array3.length; k++)
{
boolean b = (x == array3[k]);
barray[k] = b;
if(b) {
counter++;
}
}
To answer your question in the comment, the method should be called and can be checked like this:
public static void main(String[] args) {
int[] array3 = {0,1,3,2,3,0,3,1};
int x = 3;
int[] result = removeTwo(x, array3);
for (int n : result) {
System.out.print(""+ n + " ");
}
}
On this line:
int[] array4 = new int [array3.length - counter];
You create an array with size 0, as counter is equal to array3.length at this point.
This means that you cannot access any index in that array.
You are creating
int[] array4 = new int [array3.length - counter];// 0 length array.
you can't have 0th index there. At least length should 1 to have 0th index.
BTW my suggestion, it is better to use List. Then you can do this easy.
Really an Array is the wrong tool for the job, since quite apart from anything else you will end up with stray values at the end that you cannot remove. Just use an ArrayList and that provides a removeAll() method to do what you need. If you really need arrays you can even do:
List<Integer> list = new ArrayList(Arrays.asList(array))
list.removeAll(4);
array = list.toArray();
(Exact method names/parameters may need tweaking as that is all from memory).
the simplest way is to work with a second array where you put in the correct values
something likte that
public static int[] removeTwo (int x, int[] array3)
{
int counter = 0;
int[] array4 = new int[array3.lenght];
for (int i = 0; i < array3.lenght; i ++) {
if(array3[i] == x){
array4[counter] = array3[i];
}
}
return array4;
}
anoterh way is to remove the x calue from the array3 and shift the values behind forward
The best way to remove element from array is to use List with Iterator. Try,
Integer[] array = {7, 8, 9, 4, 3, 4, 4, 2, 1};
List<Integer> list = new ArrayList(Arrays.asList(array));
for(Iterator<Integer> it=list.iterator();it.hasNext();){
if(it.next()==4){
it.remove();
}
}

Java, find intersection of two arrays

I have already read a few other stack overflow threads on this:
to find the intersection of two multisets in java
How do I get the intersection between two arrays as a new array?
public static int[] intersection (int [] x, int numELementsInX, int [] y, int numElementsInY) {
I am trying to examine two arrays as well as their number of elements (numElementsInX and numElementsInY), and return a new array which contains the common values of array x and y. Their intersection.
Example,if x is{1,3,5,7,9}and y is{9,3,9,4} then
intersection(x, 5, y, 4} should return {3, 9} or {9, 3}
I've read I need to use the LCS algorithm. Can anyone give me an example as to how to do this? Both the array and values in array are initialized and generated in another method, then passed into intersection.
Any help/clarification is appreciated.
EDIT CODE
for (int i=0; i<numElementsInX; i++){
for (int j=0; j<numElementsInY; j++){
if (x[j]==x[i]) { //how to push to new array?;
}
else{
}
}
}
The simplest solution would be to use sets, as long as you don't care that the elements in the result will have a different order, and that duplicates will be removed. The input arrays array1 and array2 are the Integer[] subarrays of the given int[] arrays corresponding to the number of elements that you intend to process:
Set<Integer> s1 = new HashSet<Integer>(Arrays.asList(array1));
Set<Integer> s2 = new HashSet<Integer>(Arrays.asList(array2));
s1.retainAll(s2);
Integer[] result = s1.toArray(new Integer[s1.size()]);
The above will return an Integer[], if needed it's simple to copy and convert its contents into an int[].
If you are fine with java-8, then the simplest solution I can think of is using streams and filter. An implementation is as follows:
public static int[] intersection(int[] a, int[] b) {
return Arrays.stream(a)
.distinct()
.filter(x -> Arrays.stream(b).anyMatch(y -> y == x))
.toArray();
}
General test
The answers provide several solutions, so I decided to figure out which one is the most effective.
Solutions
HashSet based by Óscar López
Stream based by Bilesh Ganguly
Foreach based by Ruchira Gayan Ranaweera
HashMap based by ikarayel
What we have
Two String arrays that contain 50% of the common elements.
Every element in each array is unique, so there are no duplicates
Testing code
public static void startTest(String name, Runnable test){
long start = System.nanoTime();
test.run();
long end = System.nanoTime();
System.out.println(name + ": " + (end - start) / 1000000. + " ms");
}
With use:
startTest("HashMap", () -> intersectHashMap(arr1, arr2));
startTest("HashSet", () -> intersectHashSet(arr1, arr2));
startTest("Foreach", () -> intersectForeach(arr1, arr2));
startTest("Stream ", () -> intersectStream(arr1, arr2));
Solutions code:
HashSet
public static String[] intersectHashSet(String[] arr1, String[] arr2){
HashSet<String> set = new HashSet<>(Arrays.asList(arr1));
set.retainAll(Arrays.asList(arr2));
return set.toArray(new String[0]);
}
Stream
public static String[] intersectStream(String[] arr1, String[] arr2){
return Arrays.stream(arr1)
.distinct()
.filter(x -> Arrays.asList(arr2).contains(x))
.toArray(String[]::new);
}
Foreach
public static String[] intersectForeach(String[] arr1, String[] arr2){
ArrayList<String> result = new ArrayList<>();
for(int i = 0; i < arr1.length; i++){
for(int r = 0; r < arr2.length; r++){
if(arr1[i].equals(arr2[r]))
result.add(arr1[i]);
}
}
return result.toArray(new String[0]);
}
HashMap
public static String[] intersectHashMap(String[] arr1, String[] arr2){
HashMap<String, Integer> map = new HashMap<>();
for (int i = 0; i < arr1.length; i++)
map.put(arr1[i], 1);
ArrayList<String> result = new ArrayList<>();
for(int i = 0; i < arr2.length; i++)
if(map.containsKey(arr2[i]))
result.add(arr2[i]);
return result.toArray(new String[0]);
}
Testing process
Let's see what happens if we give the methods an array of 20 elements:
HashMap: 0.105 ms
HashSet: 0.2185 ms
Foreach: 0.041 ms
Stream : 7.3629 ms
As we can see, the Foreach method does the best job. But the Stream method is almost 180 times slower.
Let's continue the test with 500 elements:
HashMap: 0.7147 ms
HashSet: 4.882 ms
Foreach: 7.8314 ms
Stream : 10.6681 ms
In this case, the results have changed dramatically. Now the most efficient is the HashMap method.
Next test with 10 000 elements:
HashMap: 4.875 ms
HashSet: 316.2864 ms
Foreach: 505.6547 ms
Stream : 292.6572 ms
The fastest is still the HashMap method. And the Foreach method has become quite slow.
Results
If there are < 50 elements, then it is best to use the Foreach method. He strongly breaks away in speed in this category.
In this case, the top of the best will look like this:
Foreach
HashMap
HashSet
Stream - Better not to use in this case
But if you need to process big data, then the best option would be use the HashMap based method.
So the top of the best look like this:
HashMap
HashSet
Stream
Foreach
With duplicate elements in array finding intersection.
int [] arr1 = {1,2,2,2,2,2,2,3,6,6,6,6,6,6,};
int [] arr2 = {7,5,3,6,6,2,2,3,6,6,6,6,6,6,6,6,};
Arrays.sort(arr1);
Arrays.sort(arr2);
ArrayList result = new ArrayList<>();
int i =0 ;
int j =0;
while(i< arr1.length && j<arr2.length){
if (arr1[i]>arr2[j]){
j++;
}else if (arr1[i]<arr2[j]){
i++;
}else {
result.add(arr1[i]);
i++;
j++;
}
}
System.out.println(result);
If you don't want to use other data structures such as a Set, then the basic idea is that you want to iterate through the elements of one of the arrays and for each value see if it appears in the other. How do you see whether it appears in the other array? Walk through the elements in the other array and for each one, see if its value is equal to the value you are looking for. I suspect that you will be best served by trying to work through this problem on your own beyond this point if your goal in taking the class is to learn to write Java well, but it you get stuck you might consider updating your question with the code that you have written so you can get more detailed feedback and pointers in the right direction.
Try this:
public static void main(String[] args) {
int[] arr1 = new int[]{1, 2, 3, 4, 5};
int[] arr2 = new int[]{3, 2, 5, 9, 11};
getIntersection(arr1, arr2);
}
public static Object[] getIntersection(int[] arr1, int[] arr2) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < arr1.length; i++) {
for (int j = 0; j < arr2.length; j++) {
if (arr1[i] == arr2[j]) {
list.add(arr1[i]);
}
}
}
return list.toArray();
}
You can find the intersection of two arrays with:
T[] result = Arrays.stream(a1)
.filter(new HashSet<>(Arrays.asList(a2))::contains)
.toArray(T[]::new);
where T should be substitutable by a reference type e.g. String, Integer, etc.
although the above may seem like it's creating a new set for each element, it's not the case at all. instead only one set instance is created.
The above code is equivalent to:
List<T> list = new ArrayList<>();
HashSet<T> container = new HashSet<>(Arrays.asList(a2));
for (T s : a1) {
if (container.contains(s)) list.add(s);
}
T[] result = list.toArray(new T[0]);
finding intersection includes duplicate using the hash map.
Output: 1 2 2 15 9 7 12
public static void main(String[] args) {
int[] arr1 = {1, 2, 2, 1, 5, 9, 15, 9, 7, 7, 12};
int[] arr2 = {1, 2, 2, 3, 4, 15, 9, 7, 12, 14};
printIntersect(arr1, arr2);
}
private static void printIntersect(int[] arr1, int[] arr2) {
Map<Integer, Integer> map = new HashMap<>();
//put first array to map
for (int i = 0; i < arr1.length; i++) {
if (!map.containsKey(arr1[i])) {
map.put(arr1[i], 1);
} else {
map.put(arr1[i], map.get(arr1[i]) + 1);
}
}
//check all value in array two
for (int i = 0; i < arr2.length; i++) {
//if exist and value>1 then decrement value
//if value is 1 remove from map
if (map.containsKey(arr2[i])) {
System.out.print(arr2[i] + " ");
if (map.get(arr2[i]) > 1) {
map.put(arr2[i], map.get(arr2[i]) - 1);
} else {
map.remove(arr2[i]);
}
}
}
}
if the arrays are sorted
int a1[]=new int[] {1,2,3,5,7,8};
int a2[]=new int [] {1,5,6,7,8,9};
// get the length of both the array
int n1=a1.length;
int n2=a2.length;
//create a new array to store the intersection
int a3[]=new int[n1];
//run the loop and find the intersection
int i=0,j=0,k=0;
while(i<n1&& j<n2) {
if(a1[i]<a2[j]) {
// a1 element at i are smaller than a2 element at j so increment i
i++;
}else if(a1[i]>a2[j]) {
// a2 element at i are smaller than a2 element at j so increment j
j++;
}else {
// intersection element store the value and increment i, j, k to find the next element
a3[k]=a1[i];
i++;
j++;
k++;
}
}
for(int l=0;l<a3.length;l++) {
System.out.println(a3[l]);
}
How to Find the Intersection of 3 unsorted arrays in Java:-
I have used the Core Java approach using for loops & using Arrays.copyOf to achieve this.
public class Intersection {
public void intersection3Arrays(int ar1[], int ar2[], int ar3[]) {
Arrays. sort(ar1);
Arrays. sort(ar2);
Arrays. sort(ar3);
int ar1Len = ar1.length;
int ar2Len = ar2.length;
int ar3Len = ar3.length;
int larArray = ar3Len > (ar1Len > ar2Len ? ar1Len : ar2Len) ? ar3Len : ((ar1Len > ar2Len) ? ar1Len : ar2Len);
System.out.println("The largest array is " +larArray);
int[] inputArray1 = Arrays.copyOf(ar1, larArray);
int[] inputArray2 = Arrays.copyOf(ar2, larArray);
int[] inputArray3 = Arrays.copyOf(ar3, larArray);
Integer[] inputArray11 = new Integer[inputArray1.length];
Integer[] inputArray22 = new Integer[inputArray2.length];
Integer[] inputArray33 = new Integer[inputArray3.length];
for (int i = 0; i < inputArray11.length; i++) {
if (inputArray11[i] == null){
inputArray1[i] = 0;
}
}
for (int i = 0; i < inputArray22.length; i++) {
if (inputArray22[i] == null){
inputArray1[i] = 0;
}
}
for (int i = 0; i < inputArray33.length; i++) {
if (inputArray33[i] == null){
inputArray1[i] = 0;
}
}
for (int i = 0; i < inputArray11.length; i++)
for (int j = 0; j < inputArray22.length; j++)
for (int k = 0; k < inputArray33.length; j++)
if (inputArray11[i] == inputArray22[j] && inputArray11[i] == inputArray33[k]) {
System.out.print(inputArray11[i]+" ");
}
}
public static void main(String[] args) {
Intersection3Arrays arrays = new Intersection3Arrays();
int ar1[] = { 1, 2, 5, 10, 20, 40, 80 };
int ar2[] = { 80, 100, 6, 2, 7, 20 };
int ar3[] = {3, 4, 15, 20, 30, 70, 80, 120};
arrays.intersection3Arrays(ar1, ar2, ar3);
}
}
If you ever wanted to implement this in python, this is one way that you can find intersection.
#find intersection
def find_intersec(list_a, list_b):
return set(list_a).intersection(list_b)
#since lists are kind of like arrays in python we use two lists
list_a = [ 4, 9, 1, 17, 11, 26, 28, 10,28, 26, 66, 91]
list_b = [9, 9, 74, 21, 45, 11, 63,10]
print(find_intersec(list_a, list_b))
I hope this example will simple one.pass two arrays and you will definitely get INTERSECTION of array without duplicate items.
private static int[] findInterserctorOfTwoArray(int[] array1, int[] array2) {
Map<Integer,Integer> map=new HashMap<>();
for (int element : array1) {
for (int element2 : array2) {
if(element==element2) {
map.put(element, element);
}
}
}
int[] newArray=new int[map.size()];
int con=0;
for(Map.Entry<Integer, Integer> lst:map.entrySet()) {
newArray[con]=lst.getValue();
con++;
}
return newArray;
}
optimised for sorted arrays using only one loop.
int a1[]=new int[] {1,2,3,5,7,8};
int a2[]=new int [] {1,5,6,7,8,9};
// sort both the array
Arrays.sort(a1);
Arrays.sort(a2);
// get the length of both the array
int n1=a1.length;
int n2=a2.length;
//create a new array to store the intersection
int a3[]=new int[n1];
//run the loop and find the intersection
int i=0,j=0,k=0;
while(i<n1&& j<n2) {
if(a1[i]<a2[j]) {
// a1 element at i are smaller than a2 element at j so increment i
i++;
}else if(a1[i]>a2[j]) {
// a2 element at i are smaller than a2 element at j so increment j
j++;
}else {
// intersection element store the value and increment i, j, k to find the next element
a3[k]=a1[i];
i++;
j++;
k++;
}
}
for(int l=0;l<a3.length;l++) {
System.out.println(a3[l]);
}
Primitive Iterator: 6 Times Faster than HashSet
Tested on sorted arrays of 10,000,000 random elements, values between 0 and 200,000,000. Tested on 10 processor i9 with 4GB heap space. Sort time for two arrays was 1.9 seconds.
results:
primitive() - 1.1 seconds
public static int[] primitive(int[] a1, int[] a2) {
List<Integer> list = new LinkedList<>();
OfInt it1 = Arrays.stream(a1).iterator();
OfInt it2 = Arrays.stream(a2).iterator();
int i1 = it1.next();
int i2 = it2.next();
do {
if (i1==i2) {
list.add(i1);
i1 = it1.next();
}
if (i1 < i2) i1 = it1.next();
if (i2 < i1) i2 = it2.next();
} while(it1.hasNext() && it2.hasNext());
if (i1==i2) list.add(i1);
return list.stream().mapToInt(Integer::intValue).toArray();
}
boxed() - 6.8 seconds
public static int[] boxed(int[] a1, int[] a2) {
return Arrays.stream(a1)
.filter(new HashSet<>(Arrays.stream(a2).boxed()
.collect(Collectors.toList()))::contains)
.toArray();
}

dynamically adding more values to an arraylist in java

still a bit new with arrays and lists in java, I would like add elements to a list dynamically, so for example if I had code like this:
List<int[]> rowList = new ArrayList<int[]>();
rowList.add(new int[] { 1, 2, 3 });
rowList.add(new int[] { 4, 5, 6 });
rowList.add(new int[] { 7, 8 });
how would I dynamically add 1,2,3,4,5,6,7 etc? thanks in advance for the help
Simply use a List<Integer> to store the numbers directly:
List<Integer> ints = new ArrayList<Integer>();
ints.add(1); // works with Java 1.5+, inboxing
ints.add(2);
Or, if you want to keep your datastructure, wrap the numbers in short arrays:
rowList.add(newValue(1));
where we have:
private int[] newValue(int a) {
int[] result = new int[1];
result[0] = a;
return result;
}
Edit
Some more Java 1.5+ magic, using varargs and autoboxing:
private int[] newValue(Integer... values) {
int[] result = new int[values.length];
for (int i = 0; i < result.length; i++)
result[i] = values[i];
return result
}
Usage:
List<int[]> rowList = new ArrayList<int[]>();
rowList.add(newValues(10, 20, 30));
rowList.add(newValues(1,2,3,4,5,6,7));
If you want to add a new int[] to the list you will first have to create and fill it. If you don't know the length the array will be I would suggest an array that will dynamically add space as your reach its limit.
After you have created this array, just pass it as an argument. Should be straight forward.
You could use a for loop if you would like to add them without writing out every single number.
for(int i = 0; i < [however many you would like]; i++) {
ints.add(i);
}
Something of this effect (using varargs if you have JDK 5 and higher).
public class ListUtils {
public static void add(List<int[]> list, int... args) {
if (list != null && args != null) {
list.add(args);
}
}
}
Now, you can do
ListUtils.add(list, 1, 2, 3, 4, 5, 6, 7);
I am not sure of what you need but I hope this example will help you :
List<Integer> rowList = new ArrayList<Integer>();
Collections.addAll(rowList, ArrayUtils.toObject(new int[] { 1, 2, 3 }));
Collections.addAll(rowList, ArrayUtils.toObject(new int[] { 4, 5, 6 }));
Collections.addAll(rowList, ArrayUtils.toObject(new int[] { 7, 8 }));
ArraysUtils is a class of apache commons really usefull to deal with primitive and object arrays.
Regards,
Diodfr

Categories