Home > Software design >  how to optimize getCommon method?
how to optimize getCommon method?

Time:04-10

I am asking if this code can be optimized. (first code). I think using getCommon is complicated (second code), I don't need to create a loop to use my method, is there an easy way to use getCommon in main class ?

public int [] getCommon(int [] array1, int [] array2) {
        int length = array1.length < array2.length ? array1.length : array2.length; // choosing the shortest length.
        int [] tempArray = new int [length]; // array to store common elements.
        int counterNewArray = 0; // counter loop for tempArray.
        for(int counter1 = 0; counter1 < array1.length; counter1  ) {
            for(int counter2 = 0; counter2 < array2.length; counter2  ) {
                if(array1[counter1] == array2[counter2]) {
                    tempArray = insertIndex(tempArray, counterNewArray, array1[counter1]); // insertIndex is another method i implemented before.
                    counterNewArray  ;
                    break;
                }
            }
        }
        // the purpose of this array is to store only common elements, because tempArray holds zeros when there is no common element.
        int [] newArray = new int [counterNewArray]; 
        int tempLength = newArray.length - 1;
        while(tempLength >= 0) newArray[tempLength] = tempArray[tempLength--];
        return newArray;
    }

the main class contains

public class mainClass {
    public static void main(String[] args) {
        array arr = new array(); // I use my class here.

        int [] num = {0,1,2,3,4,5,6,7,8,9,10};
        int [] num1 = {4,6,4,3,6,5,8,5,5,5,10};

        
        int [] newArray = arr.getCommon(num, num1);
        
        for(int counter = 0; counter < newArray.length; counter  ) System.out.println(newArray[counter]);
    }
}

CodePudding user response:

For example a solution with streams and lambdas, optimized for readability

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        int[] array1 = {0,1,2,3,4,5,6,7,8,9,10};
        int[] array2 = {4,6,4,3,6,5,8,5,5,5,10};

        Arrays.stream(getCommon(array1, array2)).forEach(System.out::println);
    }

    public static int[] getCommon(int[] array1, int[] array2){
        List<Integer> list1 = Arrays.stream(array1).boxed().collect(Collectors.toList());
        List<Integer> list2 = Arrays.stream(array2).boxed().collect(Collectors.toList());

        List<Integer> commonList = list1.stream().filter(list2::contains).collect(Collectors.toList());
        return commonList.stream().mapToInt(Integer::intValue).toArray();
    }
}
  • Related