简体   繁体   中英

How to simulteniously delete elements from two Arraylists based one same index value in java

I have two arraylists which contains two set of strings.For example List domainList contain {'gmail','yahoo','yahoo','aol'}, and list flagList contains {'Y,'N','N','Y'} .So now since yahoo is twice in the list i have to remove one 'yahoo' from this domainList and also its corresponding flag from flagList.The resuting list will be {'gmail','yahoo','aol'} and {'Y','N','Y'}.I am not sure how to do that.

Can anyone help me?

As folks have noted in the comments, you could explore creating a class to hold related information, and then use a single list of instances of this class.

However, if you really want to delete repeated elements from one list while keeping another in sync, you can use a Set to keep track of what's been seen already, and an Iterator to go through the list and remove elements that are already present in the set:

public static void main(String[] args)
{
  List<String> domainList = new ArrayList<>(Arrays.asList("gmail","yahoo","yahoo","aol"));
  List<String> flagList = new ArrayList<>(Arrays.asList("Y","N","N","N"));

  Set<String> seen = new HashSet<String>();
  Iterator<String> di = domainList.iterator();
  Iterator<String> fi = flagList.iterator();
  while(di.hasNext() && fi.hasNext())
  {
    fi.next(); // don't care about result
    String domain = di.next();
    if(!seen.add(domain)) 
    {
      di.remove();
      fi.remove();
    }
  }    
  System.out.println(domainList);
  System.out.println(flagList);
}

Output:

[gmail, yahoo, aol] 
[Y, N, N]

If your list contains strings you can use this approach:

    List<String> notUniqueList = Arrays.asList("gmail", "yahoo", "yahoo", "aol");
    List<String> uniqueList = new ArrayList<>(new LinkedHashSet<>(notUniqueList));
    for (String s : uniqueList) {
        System.out.println(s);
    }

The print result:

gmail
yahoo
aol

If you are going use a custom object instead of String.class do not forget override equals() and hashcode() methods .

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