Compare every item to every other item in ArrayList

后端 未结 5 884
孤街浪徒
孤街浪徒 2021-02-05 08:07

I\'m having trouble with what I thought should be a pretty simple problem.

I need to compare every item in an arrayList with every other item in the the list without com

相关标签:
5条回答
  • 2021-02-05 08:15

    In some cases this is the best way because your code may have change something and j=i+1 won't check that.

    for (int i = 0; i < list.size(); i++){  
        for (int j = 0; j < list.size(); j++) {
                    if(i == j) {
                   //to do code here
                        continue;
                    }
    
    }
    

    }

    0 讨论(0)
  • 2021-02-05 08:19

    This code helped me get this behaviour: With a list a,b,c, I should get compared ab, ac and bc, but any other pair would be excess / not needed.

    import java.util.*;
    import static java.lang.System.out;
    
    // rl = rawList; lr = listReversed
    ArrayList<String> rl = new ArrayList<String>();
    ArrayList<String> lr = new ArrayList<String>();
    rl.add("a");
    rl.add("b");
    rl.add("c");
    rl.add("d");
    rl.add("e");
    rl.add("f");
    
    lr.addAll(rl);
    Collections.reverse(lr);
    
    for (String itemA : rl) {
        lr.remove(lr.size()-1);
            for (String itemZ : lr) {
            System.out.println(itemA + itemZ);
        }
    }
    

    The loop goes as like in this picture: Triangular comparison visual example

    or as this:

       |   f    e    d    c    b   a
       ------------------------------
    a  |  af   ae   ad   ac   ab   ·
    b  |  bf   be   bd   bc   ·   
    c  |  cf   ce   cd   ·      
    d  |  df   de   ·         
    e  |  ef   ·            
    f  |  ·               
    

    total comparisons is a triangular number (n * n-1)/2

    0 讨论(0)
  • 2021-02-05 08:19

    The following code will compare each item with other list of items using contains() method.Length of for loop must be bigger size() of bigger list then only it will compare all the values of both list.

    List<String> str = new ArrayList<String>();
    str.add("first");
    str.add("second");
    str.add("third");
    List<String> str1 = new ArrayList<String>();
    str1.add("first");
    str1.add("second");
    str1.add("third1");
    for (int i = 0; i<str1.size(); i++)
    {
    System.out.println(str.contains(str1.get(i)));
    }
    

    Output is true true false

    0 讨论(0)
  • 2021-02-05 08:28

    What's the problem with using for loop inside, just like outside?

    for (int j = i + 1; j < list.size(); ++j) {
        ...
    }
    

    In general, since Java 5, I used iterators only once or twice.

    0 讨论(0)
  • 2021-02-05 08:32
    for (int i = 0; i < list.size(); i++) {
      for (int j = i+1; j < list.size(); j++) {
        // compare list.get(i) and list.get(j)
      }
    }
    
    0 讨论(0)
提交回复
热议问题