简体   繁体   中英

Compare,process and delete entry in Lists in Java

I have two lists with objects,where list1(names) has just fullnames without middlenams and one more list2(fullnames) has fullnames with middle names . If list1 has name like barack obama and list2 has name barack hussein obama ,which is same but with middlename. Then i have to delete the entry barack obama in list1.

I have tried below code, But it did not delete entries in list1.

public class Test {

       public static void main(String args[]) {

        List<String> names = new ArrayList<>()
        names.add("shannon sperling");
        names.add("john smith");
        names.add("Mary Smith");
        names.add("kim taylor");
        names.add("Barack obama");
        List<String> fullnames = new ArrayList<>();
        fullnames.add("Mary Elizabeth Smith");
        fullnames.add("Lou Henry Hoover");
        fullnames.add("Barack hussein obama");
        for(Object process :names)
        {
            if(fullnames.contains(process))
            {
               names.remove(process);
            }
        }
        System.out.println(names);

       }
}

List.contains() checks for same objects. "Barack obama" and "Barack hussein obama" are obviously not the same. you need to override contains() or implement an own Class implementing List and add an additional function to compare your content in the way you like. Otherwise your code-block looks good.

try this

for(Object process :names)
        {
            for(Object process1 :fullnames)
            {
            if(process1.contains(process))
            {
               System.out.println("match found");
            }
            }
        }

This is not really achievable using String.contains(characterSequence) method because the character sequence must be continuous. However, the following working code should solve your problem.

for(String fName: fullnames)
        {
            int i;
            for(i =0 ; i< names.size() ;i++)
            {
                String mName = names.get(i);
                String namePart[] = mName.split("\\s+");
                if(namePart.length > 1)
                {
                    int j = fName.indexOf(namePart[0]);
                    if( j > -1 && fName.indexOf(namePart[1], j+namePart[0].length()) > -1)
                        break;

                }
            }

            if(i < names.size())
            {
                System.out.println("removing "+names.remove(i));;

            }
        }

        System.out.println(names);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM