How do I remove duplicate numbers on ArrayList and replace them with new ones?
I want to print the numbers without them duplicating.
This is my code:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JOptionPane;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
int opt = Integer.parseInt(JOptionPane.showInputDialog("How many numbers?");
for (int i=0 ; i < opc ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("Which numbers?")));
}
Set<Integer> s = new HashSet<>();
for (Integer d : al){
if (s.add(d) == false)
JOptionPane.showMessageDialog(null,"The number " + d + " was duplicated in position " + al.lastIndexOf(d));
JOptionPane.showMessageDialog(null,"Replace new number"); //This is where I would like to replace the numbers if possible
}
JOptionPane.showMessageDialog("Your numbers without duplicates: "); //This is where it would print
}
}
}
Prevent from entering duplicate numbers when the user enters them, instead of checking and replacing them later.Do it in this place:
for (int i=0 ; i < opc ; i++) {
al.add(Integer.parseInt(JOptionPane.showInputDialog("Which numbers?")));
}
Chceck if a number already exists, if yes then ask for another not duplicated, if yes then add it and ask for next number :
for (int i=0 ; i < opc ; i++) {
int myNumber = Integer.parseInt(JOptionPane.showInputDialog("Which numbers?"));
while( true ){
if( ! al.contains( myNumber ))
al.add( myNumber );
break;
}
myNumber = Integer.parseInt(JOptionPane.showInputDialog("This number is a duplicate, enter another number again"));
}
}
======== EDIT ==================
I've corrected the example. There is missing { after if in the above (previous) one:
public class MmuClass {
public static void main(String... wwwx) {
List<Integer> lst = Arrays.asList(4, 2, 6, -6, 9);
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i < 5; i++) {
int myNumber = Integer.parseInt(JOptionPane.showInputDialog("Which numbers?"));
while (true) {
if (!al.contains(myNumber)) {
al.add(myNumber);
break;
}
myNumber = Integer.parseInt(
JOptionPane.showInputDialog("This number is a duplicate, enter another number again"));
}
al.stream().forEach(System.out::println);
}
}
}
Related
//I need to ask the user for the size of the list they want, then generate random numbers with an array list for the size list they want, and output the list. These steps I have done but then I have to output the number of odd numbers in the list using an enhanced for loop and then reprint the list without even numbers.//
import java.util.Scanner;
import java.util.ArrayList;
public class MyProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("How big would you like your list?");
int decision = scan.nextInt();
ArrayList<Integer> Rando = new ArrayList<Integer>();
for (int i = 1; i <= decision; i++)
{
Rando.add((int)(Math.random()*100 + 1));
}
System.out.println();
System.out.println(Rando);
ArrayList<Integer> evens = Rando;
for (int i = 0; i < evens.size(); i++)
{
if (evens.get(i)%2 != 0)
{
evens.remove(i);
}
}
ArrayList<Integer> odds = Rando;
for (int i = 0; i < odds.size(); i++)
{
if (odds.get(i)%2 != 0)
{
evens.remove(i);
}
}
System.out.println();
System.out.println(odds);
for(Integer number: Rando)
{
System.out.println();
System.out.println("# of Odd Numbers: "+ odds.size());
System.out.println();
break;
}
System.out.println("List Without Evens: " + evens.remove);
System.out.println();
}
}
The way you are doing it now you won't have anything left in the list.
ArrayList<Integer> evens = Rando;
...
ArrayList<Integer> odds = Rando;
This will modify the original list. You won't have anything left in the list after the first two loops, which remove the even numbers and then the odd. I think instead you should create a new list.
ArrayList<Integer> evens = new ArrayList<>();
for (int i = 0; i < Rando.size(); i++)
{
if (Rando.get(i)%2 == 0)
{
evens.add(Rando.get(i));
}
}
Now using the for-each loop becomes easier.
ArrayList<Integer> evens = new ArrayList<>();
for (int x : Rando )
{
if (x%2 == 0)
{
evens.add(x);
}
}
Remember you need to modify the loops you have now. Rando will contain no elements at all the way you have it, so you have to change the existing code or re-create the random number list each time.
I have written this code My Problem is it is taking the length. of array as input but not reading the elements of array We have to use iterator for reading all Inputs.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.*;
public class arrayl {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList < Integer > list = new ArrayList < Integer > ();
System.out.println(" Enter the length of array :");
int n = sc.nextInt();
int array[] = new int[n];
System.out.println("Enter List : ");
for (Iterator < Integer > itr = list.iterator(); itr.hasNext();) {
if (itr.next() != null) {
while (itr.hasNext()) {
Integer thisInt = itr.next();
if (thisInt % 2 == 0) {
list.add(thisInt);
}
System.out.println(" Even Index Position Sum : ");
}
}
}
}
}
Your code has several problems according to the context you have asked.
You haven't added anything to the list yet using scanner. So, how can you get the values to be calculated?
Using two loops for iterating through the list and checking again, this does not seem correct.
Printing your final output inside the loop will print it several times.
So, here is the complete code:
import java.util.*;
public class arrayl {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>();
System.out.println("Enter the length of array :");
int n = sc.nextInt();
System.out.println("Enter List : ");
for (int i = 0; i < n; i++) {
list.add(sc.nextInt());
}
Iterator<Integer> itr = list.iterator();
int sum = 0;
int count = 0;
while (itr.hasNext()) {
int val = itr.next();
if (count % 2 == 0) {
sum += val;
}
count++;
}
System.out.println("Even Index Position Sum : " + sum);
}
}
You haven't added anything to the ArrayList, so your for loop doesn't do anything. You have to add something to it first using list.add(element) where element is an int.
I am very new to java and a junior java developer.
The requirement asks to get the list of customerid and if the list contains customer ids which are repeated, then it would display the dupliate record. And if there are no customer id which are repeated then it would display no duplicate record. I have tried but stuck at the point where the customerid is repeated more than twice. My code works fine till the point the customerid is repeated twice.
For ex:
Customerid:(5 input)
123
123
234
123
234
Output(Expected)
123
234
Actual:
123
123
123
234
for Scenario where there is no duplicate element, it would print no records found.
Input:
123
234
345
456
567
Output:
No records found
Output of my code is wrong when the repetition is more than twice.
Kindly Advice.
Code:
package firstpack;
import java.util.Scanner;
public class Class9 {
public static void main(String[] args) {
int a, i;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
long[] b = new long[a];
for (i = 0; i <= (b.length - 1); ) {
do {
b[i] = sc.nextLong();
i++;
}
while (i <= a - 1);
}
System.out.println("Duplicate records :");
for (i = 0; i < b.length - 1; i++) {
for (int j = i + 1; j < b.length; j++) {
if ((b[i] == (b[j])) && (i != j)) {
System.out.println(b[j]);
}
}
}
}
//Try this code if you don't want to use set for Array uniqueness.
import java.util.*;
class MyUnique{
public static void main(String args[]){
Scanner sc= new Scanner(System.in);
ArrayList<Integer> arr= new ArrayList<Integer>();
int length=sc.nextInt();
int myarr[]= new int[length];
for(int i=0;i<length;i++){
System.out.println("enter the value of array");
int value=sc.nextInt();
if(arr.contains(value)){
System.out.println("dublicate value not add and index not increased");
i = i-1; //index will not increse
}else{
myarr[i] = value;
}
arr.add(value);
}
System.out.println("Here is the array output");
for(int m=0;m<length; m++){
System.out.print(myarr[m]+",");
}
}
}
As commented by alfasin, you should use HashSet as they don't take duplicate values. So you don't have to use any loops to check. After that just print the set and you will get the result. So use something like this :
Set<Integer> s = new HashSet<Integer>();
s.add(123);
s.add(123);
s.add(234);
s.add(123);
s.add(234);
for(Integer i : s) {
System.out.println(i);
}
When I print it I get:
234
123
Hope that helps !!
You can use LinkedHashSet to get the distinct list of inputs and counts how many same inputs are in the list.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int inputCount = sc.nextInt();
List<Long> inputArr = new ArrayList<>();
for (int i = 0; i < inputCount; i++){
inputArr.add(sc.nextLong());
}
System.out.println("==================");
Set<Long> distinctArr = new LinkedHashSet<>(inputArr);
for (Long input : distinctArr) {
if(Collections.frequency(inputArr, input) > 1){
System.out.println(input);
}
}
}
Or you could just put your result in HashSet before print out.
Set<Long> set = new HashSet<Long>();
for (i = 0; i < b.length - 1; i++) {
for (int j = i + 1; j < b.length; j++) {
if ((b[i] == (b[j])) && (i != j)) {
set.add(b[j]);
}
}
}
for (Long result: set) {
System.out.println(result);
}
Try this use set to find out if duplicate entry exists or not
public static void main(String[] args) throws IOException {
int a, i;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
long[] b = new long[a];
for (i = 0; i <= (b.length - 1); ) {
do {
b[i] = sc.nextLong();
i++;
}
while (i <= a - 1);
}
Set<Long> first = new HashSet<>();
Set<Long> duplicates = new HashSet<>();
for (i = 0; i < b.length ; i++) {
if(!first.add(b[i])) {
duplicates.add(b[i]);
}
}
String message = duplicates.size() > 0 ? "Duplicate records:": "No Duplicate entry";
System.out.println(message);
duplicates.stream().forEach(System.out::println);
//in case if you want to print unique entries
first.removeAll(duplicates);
if(first.size() > 0){
System.out.println("Unique Entries:");
first.stream().forEach(System.out::println);
}
}
You can use HashMap to store the count of each element and print only if the count is more than 1. And if you need in the order of insertion then use LinkedHashMap instead of HashMap.
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Class9 {
public static void main(String[] args) {
int a, i;
Scanner sc = new Scanner(System.in);
a = sc.nextInt();
long[] b = new long[a];
Map<Long, Integer> countMap = new HashMap<Long, Integer>();
for (i = 0; i <= (b.length - 1); ) {
do {
b[i] = sc.nextLong();
if (countMap.containsKey(b[i])) {
countMap.put(b[i], countMap.get(b[i]) + 1);
} else {
countMap.put(b[i], 1);
}
i++;
}
while (i <= a - 1);
}
System.out.println("Duplicate records :");
for (Long key : countMap.keySet()) {
if (countMap.get(key) > 1) {
System.out.println(key);
}
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to write a code which will find the duplicate value in an array. So, far I have written below code:
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
//System.out.println("Please enter the length of Array: ");
int[] array = new int[6];
for(int i =0; i<array.length;i++) {
System.out.println("Enter value for index "+i+":");
array[i] = sc.nextInt();
}
FindDuplicateInArray obj = new FindDuplicateInArray();
obj.findDupicateInArray(array);
}
public void findDupicateInArray(int[] a) {
//int pointer = a[0];
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k] && j!=k && j<k && count<=1) {
count++;
if(count==1)
System.out.println(a[j]);
}
}
}
}
But I am not getting the expected output, for example:
If I give value 1,2,1,4,3,1 then it is successfully finding the duplicate value 1.
But if I provide 2 set of duplicate value in an array, still it is finding the first duplicate.
e.g. 1,2,1,2,1,3. It is giving output only 1.
I found the reason of incorrect result which is condition of count i.e. count is set to greater than 1 and it is not matching to first if condition.
So, I have tried to reset the counter to 0 after one loop iteration, now it is giving all duplicate values but duplicate values printing twice.
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
//System.out.println("Please enter the length of Array: ");
int[] array = new int[6];
for(int i =0; i<array.length;i++) {
System.out.println("Enter value for index "+i+":");
array[i] = sc.nextInt();
}
FindDuplicateInArray obj = new FindDuplicateInArray();
obj.findDupicateInArray(array);
}
public void findDupicateInArray(int[] a) {
//int pointer = a[0];
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k] && j!=k && j<k && count<=1) {
count++;
if(count==1)
System.out.println(a[j]);
}
}
**count = 0;**
}
}
e.g. Input: 1,2,1,2,1,2, Output: 1 2 1 2
Please suggest how to get the correct result.
I do not like to use Streams or smth hight-level for solving algorythmic problem; only plain java. So this is my solution:
public static Set<Integer> findDuplicateInArray(int... arr) {
Set<Integer> unique = new HashSet<>();
Set<Integer> duplicate = new HashSet<>();
for (int val : arr)
if (!unique.add(val))
duplicate.add(val);
return duplicate;
}
In case you are able to modify incomming arr, then with some small modification, you can refuce from Set<Integer> unique.
Maybe it's easier to convert the array to list and make all the logic with the Java 8 streams api in one sentence:
Integer[] numbers = new Integer[] { 1, 2, 1, 2, 1, 3 };
List<Integer> listInteger = Arrays.asList(numbers);
listInteger.stream().filter(i -> Collections.frequency(listInteger, i) >1).collect(Collectors.toSet()).forEach(System.out::println);
Output
1
2
You are in the right way, I have just updated your method, I hope that you will understand what was your mistake:
public void findDupicateInArray(int[] a) {
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j]==a[k]) {
count++;
}
}
if(count==1)
System.out.println(a[j]);
count = 0;
}
}
Nevertheless, this will make your code running correctly, and that does not mean you have written the optimal code.
Please have a look in below code it will help you.
We have to count the no of repeatation of each element and then at the last find the count, which will tell the duplicate nos.
package com.java;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
public class FindDuplicateInArray {
public static void main(String[] args) {
int[] intArr = new int[] { 1, 2, 1, 2, 1, 3, 4, 6, 2, 8 };
Map<Integer, Integer> map = new LinkedHashMap<Integer, Integer>();
for (int i = 0; i < intArr.length; i++) {
// take first element and then matched complete array
int temp = intArr[i];
int count = 0;
for (int j = 0; j < intArr.length; j++) {
if (temp == intArr[j]) {
// element matched -- break
count++;
}
}
map.put(temp, count);
}
Set<Integer> duplicate = new LinkedHashSet<Integer>();
Set<Integer> noDuplicate = new LinkedHashSet<Integer>();
for (int i = 0; i < intArr.length; i++) {
if (map.containsKey(intArr[i])) {
System.out.println("Key :" + intArr[i] + " Value : " + map.get(intArr[i]));
if (map.get(intArr[i]) > 1) {
// means repeated character
duplicate.add(intArr[i]);
} else {
// non repeated character
noDuplicate.add(intArr[i]);
}
}
}
System.out.println("Duplicate Chars : " + Arrays.toString(duplicate.toArray()));
System.out.println("No Duplicate Chars : " + Arrays.toString(noDuplicate.toArray()));
}
}
I have the following array
ArrayList<double[]> db_results = new ArrayList<double[]>();
and I would like to add values like this
db_results.add(new double[] {0,1,2});
but in a loop like this
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
db_results.add(new double[] {val});
}
obviously this is adding a new array each time with the single value... so how do I get it to add all into one array?
double[] nums = new double[3];
for ( int i = 0 ; i <= 2; i++) {
double val = Double.parseDouble(i);
nums[i] = val;
}
db_results.add(nums);
Create the double[] first, add the numbers to it, and add that array to the List.
(The variable should likely be declared as a List, btw, not an ArrayList, unless you're specifically passing it to something that explicitly expects an ArrayList.)
With something like that :
max = 3;
double[] doubles = new double[max];
for ( int i = 0 ; i < max; ++i)
{
double val = Double.parseDouble(i);
doubles[i] = val;
}
db_results.add(doubles);
import java.util.Scanner;
class DarrayEx2
{
public static void main(String args[])
{
int a[][]=new int[3][3];
int r,c,sumr;
Scanner s=new Scanner(System.in);
for(r=0;r<a.length;r++)
{
for (c=0;c<a.length ;c++ )
{
System.out.println("enter an element");
a[r][c]=s.nextInt();
}
}
for(r=0;r<a.length;r++)
{
sumr=0;
System.out.println("elements in a["+r+"] row is");
for (c=0;c<a[1].length ;c++ )
{
System.out.println(" "+a[r][c]);
sumr = sumr+a[r][c];
}
System.out.println(" = "+sumr);
System.out.println(" ");
}
}
}
source : http://www.exceptionhandle.com/portal/java/core-java/part-12-arrays.htm