Equal values ​​in java list

How can I do to see the result of two or more identical numbers contained in the list. Everything should be based on lists, the code itself is simple, but I have no idea how to achieve the same print screen value. A.

All this is done under the 5 numbers entered in the list.

Example:

Enter 1 - 2 - 3 - 3 - 4

And the number 3 will be displayed. Repeats.

This is my code:

package generarlista; import java.util.*; public class GenerarLista { /** * @param args the command line arguments */ public static void main(String[] args) { int num; Scanner read = new Scanner (System.in); List<Integer> lista = new ArrayList<>(); System.out.println("A list of 5 integers is generated and printed equal values\n"); for (int i=1; i<6; i++){ System.out.println("Enter the value "+ i +" element to populate the list"); num = read.nextInt(); lista.add(num); } System.out.println("Data were loaded \n"); System.out.println("Values in the list are: "); Iterator<Integer> nameIterator = lista.iterator(); while(nameIterator.hasNext()){ int item = nameIterator.next(); System.out.print(item+" / "); } System.out.println("\n"); System.out.println("Equals are: "); } } 

Thank you very much!

+5
source share
1 answer

There are many different approaches that could solve this problem. This is the first thing that occurred to me to sort the ArrayList and check the neighboring characters.

 package generarlista; import java.util.*; public class GenerarLista { /** * @param args the command line arguments */ public static void main(String[] args) { int num; Scanner read = new Scanner (System.in); List<Integer> lista = new ArrayList<>(); System.out.println("A list of 5 integers is generated and printed equal values\n"); for (int i=1; i<6; i++){ System.out.println("Enter the value "+ i +" element to populate the list"); num = read.nextInt(); lista.add(num); } System.out.println("Data were loaded \n"); System.out.println("Values in the list are: "); Collections.sort(lista); List<Integer> duplicates = new ArrayList<>(); for (int i = 0; i < lista.size(); i++) { System.out.print(lista.get(i) + " "); if (i < lista.size()-1 && lista.get(i) == lista.get(i+1)) if (!duplicates.contains(lista.get(i)) duplicates.add(lista.get(i)); } System.out.println("\n"); System.out.println("Equals are: "); for (int i = 0; i < duplicates.size(); i++) { System.out.print(duplicates.get(i) + " "); } } } 
+2
source

Source: https://habr.com/ru/post/1207989/


All Articles