remove duplicate value using collection framework - java

I am trying to remove duplicate values by converting an array to an arraylist and then further converting the arraylist to a Hashset. As we know hashsets do not contain any duplicate values. But i am not getting any output. I am implementing this technique because I want to avoid using a for loop .
import java.util.*;
public class RemoveDupliucate {
public static void main(String[] args) {
int a[]= {1,2,1,3,2,15,4,6,4};
List l=Arrays.asList();
TreeSet<Integer> m=new TreeSet(l);
for(Integer i:m)
{
System.out.print(i);
}
}
i am not getting any output.

If you want to remove duplicate elements from an array, there is already a method using java 8 stream,
Arrays.stream('array').distinct().toArray();
Which will remove all the duplicate elements and return the array.
for your code,
int a[]= {1,2,1,3,2,15,4,6,4};
a = Arrays.stream(a).distinct().toArray();
this should work, if you want to remove duplicates.

This line will create an empty list, that’s why you got no output:
List l = Arrays.asList();
It should be something like
List<Integer> l = Arrays.asList(1,2,1,3,2,15,4,6,4);

It is very easy in Java 8 streams
int array[]= {1,2,1,3,2,15,4,6,4};
//Use Java 8 Streams to get distinct values from an array
int[] unique = Arrays.stream(array).distinct().toArray();
If you don't want to use Java 8 streams API you can try in below
Converting array into set
public void printDistinctElements(int[] inputArray)
{
Set<Integer> elementSet = new HashSet<Integer>();
for(int i = 0; i<inputArray.length; i++)
{
elementSet.add(inputArray[i]);
}
System.out.println("Distinct Elements");
for (int i : elementSet) {
System.out.print(" " +i);
}
}

Related

Im having trouble understanding how to pass an array to a method, and return an array list

I am having trouble finishing this intro to Java assignment. My goal is pass nums[] into the method array() and then have array() return an ArrayList containing all of the "freezing" temps found in nums[]. Any help would be appreciated
import java.util.ArrayList;
import java.util.Arrays;
public class Program73 {
public static int[] array(int[] array) {
return array;
}
public static void main(String[] args) {
int nums[] = new int[14];
System.out.println("The temperatures in the last two weeks...: ");
for(int i = 0; i < nums.length; i++) {
nums[i] = (int)(Math.random() * 11) + 50;
System.out.print(nums[i] + " ");
}
System.out.println("These 5 were below freezing...:");
}
}
An ArrayList or more generally a List is nothing more than a class that implements the List interface to facilitate manipulating collections of data.
In the case of ArrayList it uses a regular array (e.g. Object[]) to store the data while providing various methods to navigate and manipulate the list. Some specific differences from the users point of view between an ArrayList and an array are.
ArrayLists grow dynamically and do not need to be pre-allocated.
You can delete (remove) an element anywhere from an ArrayList.
You can see if the ArrayList contains a specific element.
You can easily sort an ArrayList
many other examples also exist.
None of the above capabilities are free. They are simply methods implemented in a class, acting as a front-end to an array to make writing code easier.
int [] array = new int[10];
// fill the array with ints
List<Integer> list = toList(array);
public List<Integer> toList(int[] a) {
// do something with a
// like print them out.
List<Integer> list = new ArrayList<>();
for (int i : a) {
list.add(i);
}
return list;
}

Adding Arrays to an ArrayList [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
What I am trying to do is add an array to an arraylist. I've looked at other examples that tell me to do what I am doing, but I get nonsense output when I run the program. I would also like to access certain elements of an array within the arraylist, and I have no idea how to do that.
static int elements = 10; //Or whatever number you'd like
public static void main(String[] args)
{
int[] person = new int[4];
ArrayList personID = new ArrayList();
experiment(personID, person);
}
private static void experiment(ArrayList personID, int[] person)
{
for(int i = 0; i < elements; i++)
{
person[0] = i;
person[1] = i;
person[2] = i;
person[3] = i;
personID.add(person);
}
System.out.print(personID);
}
Output:
[[I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87, [I#e1cba87]
Not that much of an explanation is needed, but I declare the array and arraylist, pass them to a function which keeps giving the array's elements different values and then, supposedly, adding the array itself to the arraylist for each iteration.
The output, though, it nothing like what I am looking for. I could do another loop to print each array element for each spot along the array list, but I don't know how to do that. I figured
System.out.print(personID.get(i[0]);
Or
System.out.print(personID.get(i)[0];
But it doesn't work and I'm lost...
Thank you for dealing with me!
It's just a problem with the way you're printing the arrays. Try this instead:
for (int[] a : personID)
System.out.println(Arrays.toString(a));
Not only are you attempting to print arrays by implicitly invoking toString, but also adding the same array over and over to the list. The variable called person is a reference to an array object. You keep changing its elements and adding the same reference.
Were your print routine to be correct, the output would only show an array of four 10s repeated 10 times.
Arrays doesn't implement its own toString() implementation it uses Object#toString() and that is why you are watching that output
getClass().getName() + '#' + Integer.toHexString(hashCode())
[I means that is an Integer array plus # followed with it's hashcode e1cba87.
One way to solve it is using Arrays.toString()
For example:
public static void main(String[] args){
int[] person = new int[4];
List<int[]> personID = new ArrayList<>();
experiment(personID, person);
//now print
for(int[] array : personID){
System.out.println(Arrays.toString(array));
}
}

Java / Printing a LinkedList node containing an array

public static void main(String[] args) {
LinkedList test = new LinkedList();
int[] numberPair;
numberPair = new int[2];
numberPair[0] = 1; numberPair[1] = 2;
test.add(numberPair);
}
How would I go about accessing the array in the first node of this list and printing it? I've tried all kinds of casting with test.getFirst(), but either it prints out the memory address or I get a long list of casting errors for objects.
Try using Arrays.toString().
See the javadoc for details.
Edit:
As other answers have pointed out, you should also use generics with your List. You should declare it as a LinkedList<int[]>. And then as you iterate over the elements, use Arrays.toString to convert each element into a string and print the result.
If using java 1.5+ use java generics like so:
LinkedList<int[]> test = new LinkedList<int[]>();
int[] top = test.getFirst();
for (int i: top){
System.out.print(i+" ");
}
System.out.println();
You should use a generic type instead of a raw type.
LinkedList<int[]> test = new LinkedList<int[]>();
When do test.getFirst(), you are getting an int array back, so just iterate through it.
int[] bla = test.getFirst();
for ( int i : bla )
System.out.println(i);
Or use
Arrays.toString(test.getFirst());

How can I dynamically add items to a Java array?

In PHP, you can dynamically add elements to arrays by the following:
$x = new Array();
$x[] = 1;
$x[] = 2;
After this, $x would be an array like this: {1,2}.
Is there a way to do something similar in Java?
Look at java.util.LinkedList or java.util.ArrayList
List<Integer> x = new ArrayList<Integer>();
x.add(1);
x.add(2);
Arrays in Java have a fixed size, so you can't "add something at the end" as you could do in PHP.
A bit similar to the PHP behaviour is this:
int[] addElement(int[] org, int added) {
int[] result = Arrays.copyOf(org, org.length +1);
result[org.length] = added;
return result;
}
Then you can write:
x = new int[0];
x = addElement(x, 1);
x = addElement(x, 2);
System.out.println(Arrays.toString(x));
But this scheme is horribly inefficient for larger arrays, as it makes a copy of the whole array each time. (And it is in fact not completely equivalent to PHP, since your old arrays stays the same).
The PHP arrays are in fact quite the same as a Java HashMap with an added "max key", so it would know which key to use next, and a strange iteration order (and a strange equivalence relation between Integer keys and some Strings). But for simple indexed collections, better use a List in Java, like the other answerers proposed.
If you want to avoid using List because of the overhead of wrapping every int in an Integer, consider using reimplementations of collections for primitive types, which use arrays internally, but will not do a copy on every change, only when the internal array is full (just like ArrayList). (One quickly googled example is this IntList class.)
Guava contains methods creating such wrappers in Ints.asList, Longs.asList, etc.
Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:
/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)
I have seen this question very often in the web and in my opinion, many people with high reputation did not answer these questions properly. So I would like to express my own answer here.
First we should consider there is a difference between array and arraylist.
The question asks for adding an element to an array, and not ArrayList
The answer is quite simple. It can be done in 3 steps.
Convert array to an arraylist
Add element to the arrayList
Convert back the new arrayList to the array
Here is the simple picture of it
And finally here is the code:
Step 1:
public List<String> convertArrayToList(String[] array){
List<String> stringList = new ArrayList<String>(Arrays.asList(array));
return stringList;
}
Step 2:
public List<String> addToList(String element,List<String> list){
list.add(element);
return list;
}
Step 3:
public String[] convertListToArray(List<String> list){
String[] ins = (String[])list.toArray(new String[list.size()]);
return ins;
}
Step 4
public String[] addNewItemToArray(String element,String [] array){
List<String> list = convertArrayToList(array);
list= addToList(element,list);
return convertListToArray(list);
}
You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.
See: Java List Tutorial
You probably want to use an ArrayList for this -- for a dynamically sized array like structure.
You can dynamically add elements to an array using Collection Frameworks in JAVA. collection Framework doesn't work on primitive data types.
This Collection framework will be available in "java.util.*" package
For example if you use ArrayList,
Create an object to it and then add number of elements (any type like String, Integer ...etc)
ArrayList a = new ArrayList();
a.add("suman");
a.add(new Integer(3));
a.add("gurram");
Now you were added 3 elements to an array.
if you want to remove any of added elements
a.remove("suman");
again if you want to add any element
a.add("Gurram");
So the array size is incresing / decreasing dynamically..
Use an ArrayList or juggle to arrays to auto increment the array size.
keep a count of where you are in the primitive array
class recordStuff extends Thread
{
double[] aListOfDoubles;
int i = 0;
void run()
{
double newData;
newData = getNewData(); // gets data from somewhere
aListofDoubles[i] = newData; // adds it to the primitive array of doubles
i++ // increments the counter for the next pass
System.out.println("mode: " + doStuff());
}
void doStuff()
{
// Calculate the mode of the double[] array
for (int i = 0; i < aListOfDoubles.length; i++)
{
int count = 0;
for (int j = 0; j < aListOfDoubles.length; j++)
{
if (a[j] == a[i]) count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = aListOfDoubles[i];
}
}
return maxValue;
}
}
This is a simple way to add to an array in java. I used a second array to store my original array, and then added one more element to it. After that I passed that array back to the original one.
int [] test = {12,22,33};
int [] test2= new int[test.length+1];
int m=5;int mz=0;
for ( int test3: test)
{
test2[mz]=test3; mz++;
}
test2[mz++]=m;
test=test2;
for ( int test3: test)
{
System.out.println(test3);
}
In Java size of array is fixed , but you can add elements dynamically to a fixed sized array using its index and for loop. Please find example below.
package simplejava;
import java.util.Arrays;
/**
*
* #author sashant
*/
public class SimpleJava {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try{
String[] transactions;
transactions = new String[10];
for(int i = 0; i < transactions.length; i++){
transactions[i] = "transaction - "+Integer.toString(i);
}
System.out.println(Arrays.toString(transactions));
}catch(Exception exc){
System.out.println(exc.getMessage());
System.out.println(Arrays.toString(exc.getStackTrace()));
}
}
}

Java dynamic array sizes?

I have a class - xClass, that I want to load into an array of xClass so I the declaration:
xClass mysclass[] = new xClass[10];
myclass[0] = new xClass();
myclass[9] = new xClass();
However, I don't know if I will need 10. I may need 8 or 12 or any other number for that matter. I won't know until runtime.
Can I change the number of elements in an array on the fly?
If so, how?
No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:
int[] oldItems = new int[10];
for (int i = 0; i < 10; i++) {
oldItems[i] = i + 10;
}
int[] newItems = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;
If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList essentially wraps an array and takes care of the logic for growing the array as required:
List<XClass> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());
Generally an ArrayList is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:
class Myclass {
private int[] items;
public int[] getItems() {
return items;
}
}
you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:
class Myclass {
private List<Integer> items;
public List<Integer> getItems() {
return Collections.unmodifiableList(items);
}
}
In java array length is fixed.
You can use a List to hold the values and invoke the toArray method if needed
See the following sample:
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
public class A {
public static void main( String [] args ) {
// dynamically hold the instances
List<xClass> list = new ArrayList<xClass>();
// fill it with a random number between 0 and 100
int elements = new Random().nextInt(100);
for( int i = 0 ; i < elements ; i++ ) {
list.add( new xClass() );
}
// convert it to array
xClass [] array = list.toArray( new xClass[ list.size() ] );
System.out.println( "size of array = " + array.length );
}
}
class xClass {}
As others have said, you cannot change the size of an existing Java array.
ArrayList is the closest that standard Java has to a dynamic sized array. However, there are some things about ArrayList (actually the List interface) that are not "array like". For example:
You cannot use [ ... ] to index a list. You have to use the get(int) and set(int, E) methods.
An ArrayList is created with zero elements. You cannot simple create an ArrayList with 20 elements and then call set(15, foo).
You cannot directly change the size of an ArrayList. You do it indirectly using the various add, insert and remove methods.
If you want something more array-like, you will need to design your own API. (Maybe someone could chime in with an existing third party library ... I couldn't find one with 2 minutes "research" using Google :-) )
If you only really need an array that grows as you are initializing it, then the solution is something like this.
ArrayList<T> tmp = new ArrayList<T>();
while (...) {
tmp.add(new T(...));
}
// This creates a new array and copies the element of 'tmp' to it.
T[] array = tmp.toArray(new T[tmp.size()]);
You set the number of elements to anything you want at the time you create it:
xClass[] mysclass = new xClass[n];
Then you can initialize the elements in a loop. I am guessing that this is what you need.
If you need to add or remove elements to the array after you create it, then you would have to use an ArrayList.
You can use ArrayList:
import java.util.ArrayList;
import java.util.Iterator;
...
ArrayList<String> arr = new ArrayList<String>();
arr.add("neo");
arr.add("morpheus");
arr.add("trinity");
Iterator<String> foreach = arr.iterator();
while (foreach.hasNext()) System.out.println(foreach.next());
As other users say, you probably need an implementation of java.util.List.
If, for some reason, you finally need an array, you can do two things:
Use a List and then convert it to an array with myList.toArray()
Use an array of certain size. If you need more or less size, you can modify it with java.util.Arrays methods.
Best solution will depend on your problem ;)
Arrays.copyOf() method has many options to fix the problem with Array length increasing dynamically.
Java API
Yes, wrap it and use the Collections framework.
List l = new ArrayList();
l.add(new xClass());
// do stuff
l.add(new xClass());
Then use List.toArray() when necessary, or just iterate over said List.
I recommend using vectors instead. Very easy to use and has many predefined methods for implementation.
import java.util.*;
Vector<Integer> v=new Vector<Integer>(5,2);
to add an element simply use:
v.addElement(int);
In the (5,2) the first 5 is the initial size of the vector. If you exceed the initial size,the vector will grow by 2 places. If it exceeds again, then it will again increase by 2 places and so on.
Where you declare the myclass[] array as :
xClass myclass[] = new xClass[10]
, simply pass in as an argument the number of XClass elements you'll need. At that point do you know how many you will need? By declaring the array as having 10 elements, you are not declaring 10 XClass objects, you're simply creating an array with 10 elements of type xClass.
Java Array sizes are fixed , You cannot make dynamic Arrays as that of in C++.
Yes, we can do this way.
import java.util.Scanner;
public class Collection_Basic {
private static Scanner sc;
public static void main(String[] args) {
Object[] obj=new Object[4];
sc = new Scanner(System.in);
//Storing element
System.out.println("enter your element");
for(int i=0;i<4;i++){
obj[i]=sc.nextInt();
}
/*
* here, size reaches with its maximum capacity so u can not store more element,
*
* for storing more element we have to create new array Object with required size
*/
Object[] tempObj=new Object[10];
//copying old array to new Array
int oldArraySize=obj.length;
int i=0;
for(;i<oldArraySize;i++){
tempObj[i]=obj[i];
}
/*
* storing new element to the end of new Array objebt
*/
tempObj[i]=90;
//assigning new array Object refeence to the old one
obj=tempObj;
for(int j=0;j<obj.length;j++){
System.out.println("obj["+j+"] -"+obj[j]);
}
}
}
Since ArrayList takes to much memory when I need array of primitive types, I prefer using IntStream.builder() for creating int array (You can also use LongStream and DoubleStream builders).
Example:
Builder builder = IntStream.builder();
int arraySize = new Random().nextInt();
for(int i = 0; i<arraySize; i++ ) {
builder.add(i);
}
int[] array = builder.build().toArray();
Note: available since Java 8.
It is a good practice get the amount you need to store first then initialize the array.
for example, you would ask the user how many data he need to store and then initialize it, or query the component or argument of how many you need to store.
if you want a dynamic array you could use ArrayList() and use al.add(); function to keep adding, then you can transfer it to a fixed array.
//Initialize ArrayList and cast string so ArrayList accepts strings (or anything
ArrayList<string> al = new ArrayList();
//add a certain amount of data
for(int i=0;i<x;i++)
{
al.add("data "+i);
}
//get size of data inside
int size = al.size();
//initialize String array with the size you have
String strArray[] = new String[size];
//insert data from ArrayList to String array
for(int i=0;i<size;i++)
{
strArray[i] = al.get(i);
}
doing so is redundant but just to show you the idea, ArrayList can hold objects unlike other primitive data types and are very easy to manipulate, removing anything from the middle is easy as well, completely dynamic.same with List and Stack
I don't know if you can change the size at runtime but you can allocate the size at runtime. Try using this code:
class MyClass {
void myFunction () {
Scanner s = new Scanner (System.in);
int myArray [];
int x;
System.out.print ("Enter the size of the array: ");
x = s.nextInt();
myArray = new int[x];
}
}
this assigns your array size to be the one entered at run time into x.
Here's a method that doesn't use ArrayList. The user specifies the size and you can add a do-while loop for recursion.
import java.util.Scanner;
public class Dynamic {
public static Scanner value;
public static void main(String[]args){
value=new Scanner(System.in);
System.out.println("Enter the number of tests to calculate average\n");
int limit=value.nextInt();
int index=0;
int [] marks=new int[limit];
float sum,ave;
sum=0;
while(index<limit)
{
int test=index+1;
System.out.println("Enter the marks on test " +test);
marks[index]=value.nextInt();
sum+=marks[index];
index++;
}
ave=sum/limit;
System.out.println("The average is: " + ave);
}
}
In Java Array Sizes are always of Fixed Length But there is way in which you can Dynamically increase the Size of the Array at Runtime Itself
This is the most "used" as well as preferred way to do it-
int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;
In the above code we are initializing a new temp[] array, and further using a for loop to initialize the contents of the temp with the contents of the original array ie. stck[]. And then again copying it back to the original one, giving us a new array of new SIZE.
No doubt it generates a CPU Overhead due to reinitializing an array using for loop repeatedly. But you can still use and implement it in your code.
For the best practice use "Linked List" instead of Array, if you want the data to be stored dynamically in the memory, of variable length.
Here's a Real-Time Example based on Dynamic Stacks to INCREASE ARRAY SIZE at Run-Time
File-name: DStack.java
public class DStack {
private int stck[];
int tos;
void Init_Stck(int size) {
stck=new int[size];
tos=-1;
}
int Change_Stck(int size){
return stck[size];
}
public void push(int item){
if(tos==stck.length-1){
int temp[]=new int[stck.length+1];
for(int i=0;i<stck.length;i++)temp[i]=stck[i];
stck=temp;
stck[++tos]=item;
}
else
stck[++tos]=item;
}
public int pop(){
if(tos<0){
System.out.println("Stack Underflow");
return 0;
}
else return stck[tos--];
}
public void display(){
for(int x=0;x<stck.length;x++){
System.out.print(stck[x]+" ");
}
System.out.println();
}
}
File-name: Exec.java
(with the main class)
import java.util.*;
public class Exec {
private static Scanner in;
public static void main(String[] args) {
in = new Scanner(System.in);
int option,item,i=1;
DStack obj=new DStack();
obj.Init_Stck(1);
do{
System.out.println();
System.out.println("--MENU--");
System.out.println("1. Push a Value in The Stack");
System.out.println("2. Pop a Value from the Stack");
System.out.println("3. Display Stack");
System.out.println("4. Exit");
option=in.nextInt();
switch(option){
case 1:
System.out.println("Enter the Value to be Pushed");
item=in.nextInt();
obj.push(item);
break;
case 2:
System.out.println("Popped Item: "+obj.pop());
obj.Change_Stck(obj.tos);
break;
case 3:
System.out.println("Displaying...");
obj.display();
break;
case 4:
System.out.println("Exiting...");
i=0;
break;
default:
System.out.println("Enter a Valid Value");
}
}while(i==1);
}
}
Hope this solves your query.
You can do some thing
private static Person [] addPersons(Person[] persons, Person personToAdd) {
int currentLenght = persons.length;
Person [] personsArrayNew = Arrays.copyOf(persons, currentLenght +1);
personsArrayNew[currentLenght] = personToAdd;
return personsArrayNew;
}
You can create array with variable containing length. Like new int[n]. And pass n dynamically as argument to method. You can also create array with maximum size you can possibly need. And also create variable to track current size. depends on what your usage is.

Categories

Resources