i have an arrayList ( named error_dub ) i want to print the duplicates only one time here is my code
for(x=0 ; x<=error_dub.size()-1 ; x++){
for(int h=x+0 ; h<=error_dub.size() ; h++){
if(error_dub.get(x).equals(error_dub.get(h) && x!=h){
System.out.println(error_dub.get(x)+" is duplicated ");
}
}
}
here the line is printed more than once so how can i printed only once ?
Use two sets (this assumes X is the class of your object):
// Returns a set of all duplicates in a list
public Set<X> getDuplicates(final List<X> list)
{
final Set<X> dups = new HashSet<X>();
final Set<X> set = new HashSet<X>();
/*
* Cycle through all elements in the original list. Add it to "set":
*
* - if the .add() method returns true, this is the first time the element is seen;
* - if it returns false, then this is not the first time, it is a duplicate:
* add it to "dups".
*/
for (final X element: list)
if (!set.add(element))
dups.add(element);
return dups;
}
Set's .add() will return false if the set is not modified as a result of the operation, which means if the element was already there.
Copy/paste that function into your existing code and replace the snippet above with:
for (final X dup: getDuplicates(error_dub))
System.out.println(dup + " is duplicated");
Important note: the getDuplicates() function as it is written will NOT respect element order. If order matters to you, replace dups with a LinkedHashSet instead of a HashSet.
you can use .add() method of set to check for duplicates. Method posted below adds list elements to set1. If element is a duplicate (.add() returns true), then element is adde to setToReturn
public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates)
{
final Set<Integer> setToReturn = new HashSet();
final Set<Integer> set1 = new HashSet();
for (Integer yourInt : listContainingDuplicates)
{
if (!set1.add(yourInt))
{
setToReturn.add(yourInt);
}
}
return setToReturn;
}
ArrayList<String> ar=new ArrayList<String>();
ArrayList<String> ar2=new ArrayList<String>();
ar.add("1");
ar.add("2");
ar.add("3");
ar.add("4");
ar.add("5");
ar.add("1");
ar.add("2");
ar.add("1");
for(int x=0;x<ar.size();x++)
{
if(!ar2.contains(ar.get(x)))
{
for(int y=x+1;y<ar.size()-1;y++)
{
if((ar.get(y).equals(ar.get(x))))
{
System.out.print("repeating "+ar.get(x));
ar2.add(ar.get(x));
break;
}
}
}
}
you can do like this.
//method to identify the duplicate elements in array list
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
public class Dup
{
public static void main(String[] args)
{
ArrayList<Integer> a=new ArrayList<Integer>();
System.out.println("enter elements");
int g;
Scanner b= new Scanner(System.in);
for(int i=0;i<10;i++)
{
g=b.nextInt();
a.add(g);
}
HashSet<Integer> c=new HashSet<Integer>();
ArrayList<Integer> d=new ArrayList<Integer>();
for (Integer y : a)
{
if (c.contains(y))
{
d.add(y);
}
else
c.add(y);
}
System.out.println("original elements are:"+c);
System.out.println("duplicate elements are:");
for(Integer h:d)
{
System.out.println(h);
}
}
}
Related
For example, there is an arraylist: 40 8 6 3 7 5 2, and I want to left shift them by 2 post. And then expected output is 6 3 7 5 2. I have wrote the following code, but it generate nothing
Code:
import java.util.ArrayList;
class ArrayLinearListRev extends ArrayLinearList{
public ArrayList<Integer> leftSh(int post, ArrayList<Integer>
alist2)
{
ArrayList<Integer> LeftshifedList = new ArrayList<Integer
();
for (int i = alist2.size(); i <= post; i++)
{
LeftshifedList.remove(alist2.get(i));
}
return LeftshifedList;
}
public void printElements(ArrayList<Integer> alist2)
{
for (int i = 0; i < alist2.size(); i++) {
System.out.print(alist2.get(i) + " ");
}
}
}
public class ArrayLinearListFun {
public static void main(String[] args)
{
ArrayLinearListRev obj = new ArrayLinearListRev();
ArrayList<Integer> x = new ArrayList<Integer>();
x.add(0, new Integer(2));
x.add(1, new Integer(5));
x.add(2, new Integer(7));
x.add(3, new Integer(3));
x.add(4, new Integer(6));
x.add(5, new Integer(8));
x.add(6, new Integer(40));
System.out.print("The list is: ");
obj.printElements(x);
x=obj.leftSh(2, x);
System.out.print("\nThe list is: ");
obj.printElements(x);
}
}
Your leftSh method returns an empty List. Assuming you don't want your method modify the original List, you should initialize LeftshifedList to be a copy of the original List.
You simply need to remove the element at index 0 and repeat post times.
public ArrayList<Integer> leftSh(int post, ArrayList<Integer> alist2)
{
ArrayList<Integer> LeftshifedList = new ArrayList<>(alist2); // create a copy of input List
for (int i = 1; i <= post; i++) { // remove the first post elements
LeftshifedList.remove(0);
}
return LeftshifedList;
}
Just remove first two elements.
public ArrayList<Integer> leftSh(int post, ArrayList<Integer> alist2) {
alist2.remove(0);
alist2.remove(0);
return alist2;
}
I need help to make a main method to test this program I've made for an assignment
Write a method to merge two linked lists of integers that are sorted into descending order. The result should be a third linked list that is the sorted combination of the original lists. Do not destroy the original lists.
import java.util.Iterator;
import java.util.LinkedList;
public class Exercise6
{
public static LinkedList<Integer> merge(LinkedList<Integer> a,LinkedList<Integer> b)
{
//Initialize variables
LinkedList<Integer> result = new LinkedList<Integer>();
Iterator<Integer> aI = a.iterator();
Iterator<Integer> bI = b.iterator();
int aTemp = 0;
int bTemp = 0;
//Get the first values from both lists using the next method
aTemp = aI.next();
bTemp = bI.next();
while(aI.hasNext() && bI.hasNext())
{
//Comparing the two elements
if(aTemp > bTemp)
{
result.add(bTemp);
bTemp = bI.next();
}
}
if(!aI.hasNext())
{
result.add(aTemp);
}
while(aI.hasNext())
{
result.add(aTemp);
aTemp = aI.next();
}
while(bI.hasNext())
{
result.add(bTemp);
bTemp = bI.next();
}
if(!aI.hasNext())
{
result.add(aTemp);
}
else
{
result.add(bTemp);
}
return result;
}
}
I think this is all you are asking for:
LinkedList<Integer> list1 = new LinkedList<Integer>();
list1.add(9);
list1.add(7);
list1.add(3);
LinkedList<Integer> list2 = new LinkedList<Integer>();
list1.add(8);
list1.add(5);
list1.add(1);
Exercise6 test = new Exercise6();
test.merge(list1,list2)
First, you are missing an else for your if in while(aI.hasNext() && bI.hasNext()). Next, I would strongly recommend you program to the List interface (instead of the concrete LinkedList type). Also, I would make the merge method generic on some comparable type T. Something like,
public static <T extends Comparable<? super T>> List<T> merge(List<T> a, List<T> b) {
// Initialize variables
List<T> result = new LinkedList<>();
Iterator<T> aI = a.iterator();
Iterator<T> bI = b.iterator();
// Get the first values from both lists using the next method
T aTemp = aI.hasNext() ? aI.next() : null;
T bTemp = bI.hasNext() ? bI.next() : null;
while (aI.hasNext() && bI.hasNext()) {
// Comparing the two elements
if (aTemp.compareTo(bTemp) < 0) {
result.add(bTemp); // <-- add the right-hand side
bTemp = bI.next();
} else {
result.add(aTemp); // <-- add the left-hand side
aTemp = aI.next();
}
}
// Add the final two values from the loop.
if (aTemp.compareTo(bTemp) < 0) {
result.add(bTemp);
result.add(aTemp);
} else {
result.add(aTemp);
result.add(bTemp);
}
while (aI.hasNext()) { // Add any remaining values from a
result.add(aI.next());
}
while (bI.hasNext()) { // Add any remaining values from b
result.add(bI.next());
}
return result;
}
Then you can test merge like
public static void main(String[] args) {
System.out.println(merge(Arrays.asList(6, 4, 2), Arrays.asList(5, 3, 1)));
System.out.println(merge(Arrays.asList("bat", "ant"),
Arrays.asList("dog", "cat")));
}
I get
[6, 5, 4, 3, 2, 1]
[dog, cat, bat, ant]
So do you write your code without ever testing it? I would suggest you get familiar with writing driver classes since as your code gets bigger you will need to test it along the way.
Create another class in the same package of your Exercise class: you can call it ExerciseDriver. Import classes as needed.
Declare Initialize and populate two linked lists. Declare a third linked lost to store the result.
Call the static method of your Exercise6 class
Print the result to verify
You could do something like:
import java.util.LinkedList;
public Class ExcerciseDriver{
public static void main (String[] args){
LinkedList<Integer> list1 = new LinkedList<>();
LinkedList<Integer> list2 = new LinkedList<>();
LinkedList<Integer> resultList;
list1.add(77);
list1.add(7);
list1.add(6);
list2.add(100);
list2.add(43);
list2.add(8);
resultList = Excercise6.merge(list1, list2);
System.out.println(resultList);
}
}
Now all you have to do is running the main method and verify the correctness of your algorithm
I am trying to get a hang of using custom comparator with TreeSet. However, it seems like something is wrong. I see duplicates no matter whether I use custom equals or the compare from comparator.. Any idea where is the mistake?
Below is the code: (Please look at comments to follow)
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;
public class TreemapTest {
public static void main(String[] args) {
//Take an array of integers
int list[] = { 1,2,3,4,2,4,2,5 };
//Create a list of custom objects
ArrayList<Element> elements = new ArrayList<Element>();
//Populate the list with values from int array
for (int v : list){
elements.add(new Element(v));
}
/** Attempt to create a treeset from the arraylist */
// Create the Treeset with custom comparator
TreeSet<Element> nt = new TreeSet<Element>(new Comparator<Element>(){
public int compare(Element a, Element b){
System.out.println("Comparing "+ a.val + " and "+ b.val);
if ( a.val == b.val )
return 0;
if ( (a.val - b.val) > 0 )
return 1;
return -1;
}
});
// Add the elements into the treeset
for (Element elem: elements ){
nt.add(elem);
}
// Output shall not contain duplicates
for (Element elem: elements ){
System.out.print(":"+elem.val);
}
}
}
class Element {
public int val;
Element(int v){
val = v;
}
// boolean equals(Element e){
// return this.val == e.val;
//
// }
}
You are printing the elements list again, change it to nt set.
// Output shall not contain duplicates
for (Element elem: nt){
System.out.print(":"+elem.val);
}
all I have list containing Duplicate values I want somehow to get only Unique values from it and store it another list or set.So that I can perform some operation on it.
My code:
{
List<Integer[]> list1 = new ArrayList<Integer[]>();
list1.add(new Integer[] { 1,10 });
list1.add(new Integer[] { 1,10 });
list1.add(new Integer[] { 1,10 });
list1.add(new Integer[] { 2,10 });
list1.add(new Integer[] { 1,10 });
list1.add(new Integer[] { 3,10 });
for(int i=0;i<list1.size();i++)
{
System.out.println("I - 0 :"+list1.get(i)[0]+"\t I - 1 :"+list1.get(i)[1]+"\n");
}
Set<Integer[]> uniquelist = new HashSet<Integer[]>(list1);
for(Integer[] number: uniquelist){
System.out.println(number[0]+"\t"+number[1]);
}
}
I want the result {1,10;2,10;3,10} to be in separate list.When i googled I got to know for unique we should use set as in Set<Integer[]> uniquelist = new HashSet<Integer[]>(list1); But after doing this I dont know how to access each elements Thanks in advance
Output:
1 10
2 10
1 10
3 10
1 10
1 10
You won't get the result you want using the normal Set approach. As your List contains Integer[], and then won't be considered unique by default. All the array objects are distinct. So, your Set will contain the same elements as your list. However, you can define your Custom Comparator, and use it with a TreeSet constructor.
Another way of doing it can be, define a method contains(List<Integer[]> list, Integer[] value), which checks whether your list contains that array. Define a list named uniqueList. Now, iterate over your original list, and then for each value, call contains method passing uniqueList and that value, as parameters.
Here's how your contains method would look like: -
public static boolean contains(List<Integer[]> list, Integer[] value) {
for (Integer[] arr: list) {
// We can compare two arrays using `Arrays.equals` method.
if (Arrays.equals(arr, value)) {
return true;
}
}
return false;
}
So, you can see that, checking for containment is not the same as, how it would look for just Integer.
Now, from your main method, use this code: -
List<Integer[]> unique = new ArrayList<Integer[]>();
for (Integer[] arr: list1) {
// Use your method here, to test whether this value - `arr`
// is already in `unique` List or not. If not, then add it.
if (!contains(unique, arr)) {
unique.add(arr);
}
}
for (Integer[] arr: unique) {
System.out.println(arr);
}
I would rather use a Set implementation in this case. Use LinkedHashSet if you want your elements to be ordered.
You could declare a class IntegerPair to hold your pairs:
class IntegerPair {
private int key;
private int value;
public IntegerPair(int k, int v) {
key = k;
value = v;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
public int hashCode() {
return key * value;
}
public boolean equals(Object o) {
if (!(o instanceof IntegerPair)) {
return false;
}
IntegerPair other = (IntegerPair) o;
return key == other.key && value == other.value;
}
}
Declare it this way:
Set<IntegerPair> set = new LinkedHashSet<IntegerPair>();
Instead of putting new Integer[] values, just do set.add(new IntegerPair(1, 10));
You can loop through your elements using the foreach approach:
for (IntegerPair value : set) {
System.out.println(value.getKey() + " = " + value.getValue());
}
You can access elements by Iterator or by using for each loop
for(Integer number: setOfNumbers){
System.out.println(number);
}
Put them into set using your custom comparator like following:
new TreeSet(list1, new Comparator<Integer[]>() {
public int compare(Integer[] one, Integer[] two) {
int n = one.length;
for (int i = 0; i < n; i++) {
int comp = one.compareTo(two);
if (comp != 0) {
return comp;
}
}
return 0;
}
});
Pay attention that I used TreeSet that can accept custom comparator. It is because you are dealing with arrays. If however you define your own class that holds 2 int values you can make it to implement equals() and hashCode() that allows using any Set implementation.
the Integer[] number in your for loop is an array. to get the values inside you have to use number[index] instruction. to do that you can either do a classic while or for loop using a variable as an index
for(int i=0;i<number.length;i++) {
...
}
or a foreach loop:
for(Integer num : number){
...
}
This may help you...
public static void main(String [] args){
Set<Integer []> set = new TreeSet<Integer []>(new Comparator<Integer[]>(){
public int compare(Integer[] o1, Integer[] o2) {
if(o1.length == o2.length){
for(int i = 0; i < o1.length; i++){
if(o1[i] != o2[i]){
return -1;
}
}
return 0;
}
return -1;
}
});
set.add(new Integer[]{1,2});
set.add(new Integer[]{1,2});
set.add(new Integer[]{1,2});
set.add(new Integer[]{1,3});
int j = 0;
for(Integer[] i: set){
System.out.println("\nElements: "+j);
j++;
for(Integer k : i){
System.out.print(k+" ");
}
}
}
You need to use Comparator to compare two elements of same. As we don't have comparator for Array, Set will use actual object to compare.. using comparator you will have to tell set that this two arrays are same and do not add other same array
Try Table collection in Google-guava.
Example :
Table<Integer, Integer, Integer[]> sampleTable = HashBasedTable.create();
sampleTable.put(1, 10, new Integer[] { 1,10 });
sampleTable.put(2, 10, new Integer[] { 2,10 });
sampleTable.put(1, 10, new Integer[] { 1,10 });
So it will overwrite the duplicate values. Finally you have only unique values.
Here is my code:
import java.util.*;
public class Multiply {
public static void main(String[] args) {
LinkedList<Integer>num = new LinkedList<Integer>();
num.add("1");
num.add("2");
num.add("3");
num.add("4");
num.add("5");
product( num );
}
public static void product(LinkedList<Integer> list) {
int index = 0;
Iterator<Integer>productw = list.iterator();
Integer next = productw.next()
while (productw.hasNext()) {
index++;
System.out.println("The product of the numbers is = " + num);
}
}
}
Initially have a multiplication identity ( i.e., 1 ) before your while loop. And keep multiplying to it the iterator values.
Psuedo - code :
public static void product(LinkedList<Integer> list)
{
Iterator<Integer>productw = list.iterator();
int result = 1;
for( int i=0; i<productw.size(); ++i ) {
result *= productw.get(i) ;
}
// result has the answer
}
Edit 1:
The above loop assumes that the list has at least 1 element. If list has no elements, then zero must be the answer which I assume you can easily program it.
You need to define an initial value for the product
And then change it in the loop
Also...Your loop will print the statement multiple times- you don't want that- right ?
HTH