There is a code with two cycles. The first enumerates the first element of the cycle. The second cycle enumerates 2 elements of the cycle and compares between them.

for (String s1 : list) { int count = 0; for (String s2 : list) { if (s1.equals (s2)) { count++; result.put (s1, count); } } 

I would like to do this in one fori loop so that the index element 0 is compared with the index of element 1, how can this be done without falling out of the cycle?

  • one
    Something you all too cleverly described. Maybe we should try to somehow describe the question more clearly, otherwise I personally see only the porridge from the names. In any case, it is worth looking at the contains( ) method that both HashSet ( HashSet: contains () ) and ArrayList ( ArrayList: contains () ) has - Alex Krass
  • What do you need to compare? The length of s1 and s2? Their contents? According to the code, you are comparing the contents, and talking about indexes. How do you organize an array of strings? - Konstantin_SH
  • compare the elements in short, find the same words in the list, that is, the lines - user319033

2 answers 2

 List<String> list = new ArrayList<String>(); list.add("Sckoriy"); list.add("Sckoriy"); list.add("Sergey"); for(int i = 0 ; i < list.size() - 1 ; i++){ if(list.get(i).equals(list.get(i+1)){ //Strings are same! } } 

    In general, you can compare the current element of the array with the following

      int arr []= new int [5]; for(int i=0; i<arr.length; i++){ int j = i+1; if (arr[i]==arr[j]){ // Пишем что нужно сделать if (j>arr.length){ break; } } } 
    • Hm, what will you do if you have i = 4? Get 6 array elements if you only have 5 of them? - Sckoriy
    • @Sckoriy oops .. Correct - Konstantin_SH
    • In general, this 0-index is terrible. I’m so tense because of it, they say it’s necessary to count from 0. - Sckoriy
    • @Sckoriy Get used to it, this is not the worst thing in programming)) - Konstantin_SH
    • then this option is not possible or as - user319033