Count items common to both the lists but with different prices | Java implementation to count items common to both the lists but with different prices ; Details of an item ; comparator function used for sorting ; Function to search ' str ' in ' list2 [ ] ' . If it exists then price associated with ' str ' in ' list2 [ ] ' is being returned else - 1 is returned . Here binary search technique is being applied for searching ; if true the item ' str ' is in ' list2' ; item ' str ' is not in ' list2' ; Function to count items common to both the lists but with different prices ; sort ' list2' in alphabetcal order of items name ; initial count ; get the price of item ' list1 [ i ] ' from ' list2' if item in not present in second list then - 1 is being obtained ; if item is present in list2 with a different price ; Required count of items ; Driver code
import java . util . * ; class GFG { static class item { String name ; int price ; item ( String name , int price ) { this . name = name ; this . price = price ; } } ; static class Com implements Comparator < item > { public int compare ( item a , item b ) { return a . name . compareTo ( b . name ) ; } } static int binary_search ( item list2 [ ] , int low , int high , String str ) { while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( list2 [ mid ] . name . compareTo ( str ) == 0 ) return list2 [ mid ] . price ; else if ( list2 [ mid ] . name . compareTo ( str ) < 0 ) low = mid + 1 ; else high = mid - 1 ; } return - 1 ; } static int countItems ( item list1 [ ] , int m , item list2 [ ] , int n ) { Arrays . sort ( list2 , new Com ( ) ) ; int count = 0 ; for ( int i = 0 ; i < m ; i ++ ) { int r = binary_search ( list2 , 0 , n - 1 , list1 [ i ] . name ) ; if ( ( r != - 1 ) && ( r != list1 [ i ] . price ) ) count ++ ; } return count ; } public static void main ( String [ ] args ) { item [ ] list1 = { new item ( " apple " , 60 ) , new item ( " bread " , 20 ) , new item ( " wheat " , 50 ) , new item ( " oil " , 30 ) } ; item list2 [ ] = { new item ( " milk " , 20 ) , new item ( " bread " , 15 ) , new item ( " wheat " , 40 ) , new item ( " apple " , 60 ) } ; int m = list1 . length ; int n = list2 . length ; System . out . print ( " Count ▁ = ▁ " + countItems ( list1 , m , list2 , n ) ) ; } }