Removing duplicates from an Array that contains multiple String elements - java

I want to remove duplicate String values inside my String[], but I am not sure quite how to do that.
Heres an example:
public static void main(String[] args){
String[] listofWords = new String [5];
listofWords[0] = "BMW";
listofWords[1] = "Audi";
listofWords[2] = "Mercedes";
listofWords[3] = "Audi";
listofWords[4] = "BMW";
for(int i = 0; i<listofWords.length-1; i++){
system.out.println(listofWords[i]);
}
}
How would I got about deleting the duplicates in this array and only have one of each make?

You can convert your String[] to Set:
String [] listofWords = new String [5];
listofWords [0] = "BMW";
listofWords [1] = "Audi";
listofWords [2] = "Mercedes";
listofWords [3] = "Audi";
listofWords [4] = "BMW";
Set<String> set = new HashSet<String>(Arrays.asList(listofWords));
System.out.println(set); //prints [Audi, Mercedes, BMW]
You can convert the Set back to String[] like this:
listofWords = set.toArray(new String[set.size()]);

I would recommend this solution using Java 8 streams
String[] result = Arrays.stream(listofWords).distinct().toArray(s -> new String[s]);
This also addresses the memory concerns you have expressed in the comments. It will just create an array with enough size to store distinct values and store the result there.
As a side note you could have initialized listofWords more easily like this
String[] listofWords = {"BMW", "Audi", "Mercedes", "Audi", "BMW"};

If memory is not a concern, convert to a set and back to array, like:
Set<String> mySet = new HashSet<String>(Arrays.asList(listofWords));
listofWords = mySet.toArray(new String[mySet.size()]);
If you have memory limits then you should sort the array:
Arrays.sort(listofWords);
Then remove the duplicates, like this:
public static int removeDuplicates(String[] A) {
int length=A.length;
if(length==0 || length==1) return length;
int i=1;
for(int j=1; j<length; j++){
if(!A[j].equals(A[j-1])){
A[i]=A[j];
i++;
}
}
if(i<length) A[i]=null;
return i;
}
This method will remove the duplicates and return the new array size.
Eg.
public static void main(String[] args) {
String[] listofWords = new String [5];
listofWords[0] = "BMW";
listofWords[1] = "Audi";
listofWords[2] = "Mercedes";
listofWords[3] = "Audi";
listofWords[4] = "BMW";
Arrays.sort(listofWords);
int n=removeDuplicates(listofWords);
for(int i = 0; i<n; i++){
System.out.println(listofWords[i]);
}
}

//JAVA-8 - Remove Duplicates
List li1 = new ArrayList<>(Arrays.asList(10, 22, 10, 20, 11, 22));
System.out.println("Duplicate elements: " + li1);
// Create new list from elements of original list
List li2 = (List) li1.stream().distinct().collect(Collectors.toList());
// ArrayList with duplicates removed
System.out.println("Non-duplicate elements: " + li2);

It is straightforward to do in-place if you don't need to preserve the order of appearance in the array: sort the array first and use two pointers to iterate through the array:
Arrays.sort(listofWords);
int i = 0, j = 0;
while (j < listofWords.length) {
// Copy the element from the j-th position to the i-th position.
listofWords[i] = listofWords[j];
// Increment j while the word at position j equals the word at position i.
while (j < listofWords.length && listofWords[j].equals(listofWords[i])) {
++j;
}
// Increment i, to be the next unique element index.
++i;
}
// i currently points to the element after the last non-duplicate element, so
// ideally we would throw away elements [i..listofWords.length)
// However, you can't resize an array in Java.
// This loop just nulls out the remaining elements, since their contents are all
// already in the array.
while (i < listofWords.length) {
listofWords[i++] = null;
}

You can try the below solution :
public static void main(String[] args) {
String strArray[] = new String[]{"bmw","audi","bmw","honda","Yamaha","Yamaha","maruti","hyundai","hyundai"};
HashSet setOfStrings= new HashSet<String>();
for(int i=0;i<strArray.length;i++){
boolean result=setOfStrings.add(strArray[i]);
if(!result){
System.out.println("duplicate elements include...."+strArray[i]);
}
}
Object[] newString= new Object[strArray.length];
newString=setOfStrings.toArray();
System.out.println("Array without Duplicates......."+Arrays.toString(newString));
}

import java.util.Arrays;
/**
* #author Kishore Diyyana
* Simple Bruteforce approach
*/
public class RemoveDupilcates {
public static void main(String[] args) {
RemoveDupilcates removeDups = new RemoveDupilcates();
removeDups.removeDups();
}
public void removeDups() {
int[] numbers = new int[] {10, 22, 10, 20, 11, 22};
int[] temp = new int [numbers.length];
int count = -1;
for (int i=0; i<numbers.length;i++) {
boolean hasFound = false;
for (int j = i+1; j< numbers.length; j++) {
if (numbers[i] == numbers[j]) {
hasFound = true;
break;
}
}
if (!hasFound) {
count++;
System.out.println(numbers[i]);
temp[count] = numbers[i];
}
}
int[] outpout = null;
if (count < numbers.length) {
outpout = new int [count];
System.arraycopy(temp, 0, outpout, 0, count);
}
System.out.println(Arrays.toString(outpout));
}
}

Related

Look for duplicate values in a String[] without using Sets, Lists, ArrayLists?

Lets say we have this array: String[] arr1 = {"a", "b", "c", "a"};
What I'm trying to do is remove duplicate String (In this case "a") and add its value to another String[] called duplicates. When the duplicate is added to the "duplicates" array, the amount of times it occured wrongfully in the array arr1 is concatenated next to it. (recurredValue + amount) so in this example it would be a 1. I have searched for this before and all of them included usage of Lists, ArrayLists, or Sets. Please do not use any of them.
Use below code:-
public static String[] removeDuplicates(String[] numbersWithDuplicates) {
// Sorting array to bring duplicates together
Arrays.sort(numbersWithDuplicates);
String[] result = new String[numbersWithDuplicates.length];
String[] duplicate = new String[numbersWithDuplicates.length];
String previous = numbersWithDuplicates[0];
result[0] = previous;
int counter=1;
int duplicateCounter=0;
for (int i = 1; i < numbersWithDuplicates.length; i++) {
String ch = numbersWithDuplicates[i];
if (previous != ch) {
result[counter++] = ch;
}
else
{
duplicate[duplicateCounter++]=ch;
}
previous = ch;
}
for (int i = 0; i < result.length; i++) {
System.out.println(result[i]);
}
System.out.println("Duplicate Values are ---");
for (int i = 0; i < duplicate.length; i++) {
System.out.println(duplicate[i]);
}
return result;
}
maybe something like this you can use
public static void main(String[] args) {
String[] arr1 = {"a", "b", "c", "a", "a"};
String[] duplicates = new String[arr1.length];
boolean d = false;
int count = 0;
String dup = "";
for(int i = 0;i < arr1.length;i++){
count = 0;
dup = "";
d = false;
for(int j = 0;j < arr1.length;j++){
if(i != j){
if(arr1[i].equals(arr1[j]) && !arr1[i].equals("")){
arr1[j] = "";
d = true;
count++;
dup = arr1[i];
}
}
}
if(d){
duplicates[i] = dup + count;
d = false;}
}
for(int k = 0;k < duplicates.length;k++)
System.out.println(duplicates[k]);
}
Well, one solution is to create 2 arrays and have one hold the unique strings and the other its integer counter. As you index through your sample string array, add the unique strings and increment the incidents. This is not a very elegant or efficient solution but it should work.

How to break an Integer[] arr in more than one interger[] arrs in Java?

I have a comma separated string of IDs. I want to break this comma separated string in more than one strings if total no. of IDs are greater than 500.
What I can do:
I can convert this string in to integer array and then test it's size. Break than array in more than one arrays, and re-convert them in comma separated strings.
My code so far:
Integer[] empIdInt = null;
String tokens[]=Application.splitstr(outerArray, ",");
if(!ErmUtil.isNull(tokens) && tokens.length>0){
empIdInt=new Integer[tokens.length];
for(int i=0;i<tokens.length;i++){
empIdInt[i]=Integer.valueOf(tokens[i]);
}
}
Questions
is it right approach to tackle this problem?
if yes,how to break integer[] array in more than one arrays?
if no, what should i do?
Edit:
input : "1,2,3,4,5,6,7,8,9,10,11" //list of ids;
I want to break them more than one string if no. of ids is greater than let's say 3. As we it's 10 i.e total no. of ids. so output might be
Output "1,2,3" //1st string
"4,5,6" //2nd string
"7,8,9" //3rd string
"10" //4th string
I have use List<String> to store your data and as per count i have use List.subList(fromIndex,toIndex) method to get subList from main List.
Try below code :
String str = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15";
String[] ar_str = str.split(",");
List<String> list = Arrays.asList(ar_str);
int count = 4;
int fromIndex = 0;
int toIndex = count;
for(int i=0;i<list.size()/count;i++){
fromIndex = i * count;
toIndex = fromIndex + count;
List<String> temp = list.subList(fromIndex, toIndex);
System.out.println(temp); //Convert List into comma separated String
}
if(list.size()%count > 0){
System.out.println(list.subList(toIndex, list.size()));
}
OutPut
[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14, 15]
May this will help you.
I dont think it is a good option to convert it into integer and then count the integers when you can do the same by counting the "," (commas) in your input string.Use StringUtils class of apache which would make your task easier.Here I have assumed list size as 2,you will have to change it too 500 for your case.Try this :
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public class test {
public static void main(String[] args) {
String input = "1,2,3,4,5,6";
List<String> strList=new ArrayList<String>();
while (StringUtils.ordinalIndexOf(input, ",", 2) != -1) {
String s1 = input.substring(0, StringUtils.ordinalIndexOf(input, ",", 2));
String leftover = input.substring(StringUtils.ordinalIndexOf(input, ",", 2) + 1);
input = leftover;
strList.add(s1);
}
if(input!=""){
//for leftover strings which are less than your specified list size
strList.add(input);
}
System.out.println(strList);
}
}
public static List<String> breakStrings(String idListString) {
int limit = 3;
char separator = ',';
String[] idList = idListString.split("\\" + separator);
List<String> finalList = new ArrayList<String>();
if (idList != null && idList.length > 3) {
int j = 0;
int index = 0;
StringBuffer oneList = null;
while (j < idList.length) {
oneList = new StringBuffer();
for (int i = 0; i < limit && index < idList.length; i++) {
boolean isLast = (i + 1) == limit
|| (index + 1) == idList.length;
oneList.append(idList[index++]);
if (!isLast) {
oneList.append(separator);
}
}
finalList.add(oneList.toString());
j += limit;
}
} else {
finalList.add(idListString);
}
return finalList;
}
This will give you list of final strings according to your requirement. Hope this will help you.
Check this
int[] test={10212,10202,11000,11000,11010};
ArrayList<Integer> test2 = new ArrayList<Integer>();
for(int i = test.length -1; i >= 0; i--){
int temp = test[i];
while(temp>0){
test2.add(0, temp%10); //place low order digit in array
temp = temp /10; //remove low order digit from temp;
}
}
To get the count of ID in string and divide it into multiple Integer arrays you can do something like this.
String str = "1234,567,123,4567,890";
String strArray[] = str.split(",");
if (strArray.length > 500) {
Integer[][] ids = new Integer[300][2];
int j = 0;
int i = 0;
for (String s : strArray) {
if (i < 2) {
ids[j][i] = Integer.parseInt(s);
} else {
i = 0;
j = j + 1;
}
}
}
}

How to print the string without duplicate?

I tried to print the string without duplicate but i not getting the proper output and here I exposed my code snippets.
class Duplicatestring
{
public static void main(String [] args)
{
String word = "";
String[] ip ={"mani" ," manivannan","raghv ","mani"};
for(int i =0; i<ip.length; i++)
{
for(int j = i+1; j<=ip.length; j++)
{
if(ip[i].equals(ip[j])){
word = word+ip[i];
}
}
System.out.println(word);
}
}
}
And one more thing is I don't want use the collections that is my task and pleas give any proper solution for this.
Example:
Input -> {mani, manivanna,raghv, mani};
output -> {mani, manivanna,raghv}
If you don't want to use collections then I assume it's a homework, so I don't want to provide you a full solution, but I'll guide you.
You can have a helper array of the size of the original array. Now you write two nested loops and for each word, if you find a duplicate, you mark the helper array with 1.
After this procedure you'll have something like this in the helper array:
[0,0,0,1]
Now you iterate on the arrays in parallel and print the element only if the corresponding index in the helper array is 0.
Solution is O(n2).
Your loop is incorrect.
To solve the problem, you can use a Set to eliminate duplicated words.
If the problem must be solved by O(n^2) loops, the following code will work:
public class Duplicatestring {
public static void main(String[] args) {
String[] ip = { "mani", " manivannan", "raghv ", "mani" };
for (int i = 0; i < ip.length; i++) {
boolean duplicated = false;
//search back to check if a same word already exists
for (int j = i - 1; j >= 0; j--) {
if(ip[i].equals(ip[j])) {
duplicated = true;
break;
}
}
if(!duplicated) {
System.out.println(ip[i]);
}
}
}
}
if you want to remove the duplicate from the array call the below method and pass the array has the duplicate values.. it will return you the array with non-duplicate values..
call method here
ip = removeDuplicates(ip);
public static int[] removeDuplicates(int[] arr){
//dest array index
int destination = 0;
//source array index
int source = 0;
int currentValue = arr[0];
int[] whitelist = new int[arr.length];
whitelist[destination] = currentValue;
while(source < arr.length){
if(currentValue == arr[source]){
source++;
} else {
currentValue = arr[source];
destination++;
source++;
whitelist[destination] = currentValue;
}
}
int[] returnList = new int[++destination];
for(int i = 0; i < destination; i++){
returnList[i] = whitelist[i];
}
return returnList;
}
it will return you the non duplicates values array..!!
u may try this:
public class HelloWorld{
public static void main(String []args){
String[] names = {"john", "adam", "will", "lee", "john", "seon", "lee"};
String s;
for (int i = 0; names.length > i; i ++) {
s = names[i];
if (!isDuplicate(s, i, names)) {
System.out.println(s);
}
}
}
private static boolean isDuplicate(String item, int j, String[] items) {
boolean duplicate = Boolean.FALSE;
for (int i = 0; j > i; i++) {
if (items[i].equals(item)) {
duplicate = Boolean.TRUE;
break;
}
}
return duplicate;
}
}
output
john
adam
will
lee
seon
if string order does not matter for you, you can also use the TreeSet.. check the below code.. simple and sweet.
import java.util.Arrays;
import java.util.List;
import java.util.TreeSet;
public class MyArrayDuplicates {
public static void main(String a[]){
String[] strArr = {"one","two","three","four","four","five"};
//convert string array to list
List<String> tmpList = Arrays.asList(strArr);
//create a treeset with the list, which eliminates duplicates
TreeSet<String> unique = new TreeSet<String>(tmpList);
System.out.println(unique);
System.out.println();
Iterator<Integer> iterator = unique.iterator();
// Displaying the Tree set data
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
}
it will print as -
[five, four, one, three, two]
five
four
one
three
two

compare list and array

I need to compare the value from List with the value from array.
I wrote the following:
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
for (int i = 0; i < l.size(); i++){
v = "";
s = "";
//System.out.println(l.get(i));
for (int j = 0; j < arr.length; j++){
if (l.get(i).equals(arr[j])){
s = i + "";
}else{
s = arr[i];
}
v = v + s + ",";
}
System.out.println(v);
}
}
}
I obtain the following
0,test,test,
c,c,1
but I need the result like this:
0, c, 1,
Looking at your expected result I guess the requirement like that:
for each element in the array, check if it is on the list. If it is on the list, print the index from the list for this element, otherwise print the element itself. So the algorithm should do:
array[0] = "test" -> found at index 0 -> print "0"
array[1] = "c" -> not found -> print "c"
array[2] = "b" -> found at index 1 -> print "1"
The outer loop should iterate over the array. Then, for each array item, iterate over the list until you find the same element. For a first draft, don't collect the output in a string but print it immediatly. You can create the string when the algorithm works as expected.
You have six iterations, each of which inserts something into the output.
You want three iterations, each of which checks for membership in the first list. You can do that with the List.contains() method. (If the list were long, you might want to consider using a Set instead of a List, to allow checking set membership more quickly.)
How about this:
public static void main(String[] args) {
// TODO code application logic hereut
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String v = "";
String s = "";
String[] arr = {"test", "c", "b"};
int pointer = 0;
for (int i = 0; i < l.size(); i++){
//System.out.println(l.get(i));
for (; pointer < arr.length;){
if (l.get(i).equals(arr[pointer])){
s = i + "";
v = v + s + ",";
pointer++;
break;
}else{
s = arr[i];
}
pointer++;
v = v + s + ",";
}
}
System.out.println(v);
}
Try to break things down to their high level steps.
For each string in the array
find its place in the list
if the item is in the list
print its position
else
print the missing string
print a common and space
Once you have this you can spot that find its place in the list could be a method that returns the place in the list or -1 if it isn't in the list. Here's what I made (might have renamed a few things and used a StringBuilder but you can ignore that for the moment).
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(final String[] args) {
final List<String> listToSeach = new ArrayList<String>();
listToSeach.add("test");
listToSeach.add("b");
final String[] arrayElementsToFind = { "test", "c", "b" };
final StringBuilder output = new StringBuilder();
for (final String string : arrayElementsToFind) {
final int firstIndex = findFirstIndex(listToSeach, string);
if (firstIndex > -1) {
output.append(firstIndex);
} else {
output.append(string);
}
output.append(", ");
}
System.out.println(output);
}
private static int findFirstIndex(final List<String> list,
final String element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(element)) {
return i;
}
}
return -1;
}
}
Well I suggest this:
List<String> l = new ArrayList<String>();
l.add("test");
l.add("b");
String[] arr = {"test", "c", "b"};
for(int i=0;i<arr.length;++i){
if(l.contains(arr[i]))
s = ""+l.indexOf(arr[i]);
else
s = arr[i];
v = v + s + ",";
}
If got what you saying correct,I think this is less verbose

removing an element from String array in android

Am doing a simple android application.In that I am deleting an element from array using the following code.
arr_fav = {"1","2","3"};
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
arr_fav[1] = null;
} }
By doing this am getting the array like arr_fav = {"1",null,"3"}.But I want like arr_fav = {"1","3"}.How to delete an element.Am new to this android development.Please help me to solve this.
its better to use arraylist
arr_fav = {"1","2","3"};
List<String> numlist = new ArrayList<String>();
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id == Integer.parseInt(arr_fav[i]))
{
// No operation here
}
else
{
numlist.add(arr_fav[i]);
}
}
arr_fav = numlist .toArray(new String[numlist .size()]);
You don't.
Arrays can not be resized.
You would need to create a new (smaller) array, and copy the elements you wished to preserve into it.
A better Idea would be to use a List implementation that was dynamic. An ArrayList<Integer> for example.
Arrays in Java are not dynamic, you can use an ArrayList instead.
You can copy the array elements that you want into a new array
j = 0;
for(int i= 0;i<arr_fav.length;i++)
{
if(current_id != Integer.parseInt(arr_fav[i]))
{
arr_new[j++] = arr_fav[i];
} }
Use an ArrayList instead of an array. It supports features like deleting any element, dynamic size, and many more.
ArrayList<String> arr_fav_list = new ArrayList<String>();
arr_fav_list.addAll(arr_fav);
arr_fav_list.remove(1);
This will do the job ...
List x = new ArrayList(Arrays.asList(arr_fav));
x.remove(String.valueOf(current_id));
arr_fav = x.toArray();
try this:
ArrayList<String> rm = new ArrayList<String>();
rm .addAll(arr_fav);
rm .remove(1);
Try something like this
int[] intAry = new int[5];
// populate array with 0 to 4
for (int i=0; i < intAry.length; i++) {
intAry[i] = i;
}
List<Integer> aList = Arrays.asList(intAry); // change the array to a list of integers
aList.remove(3); // remove the item 3 (4th index)
aList.toArray(intAry); // convert list back to array
System.out.println("size of array=" + intAry.size()); // output array size should be 4
for (int i=0; i < intAry.length; i++) {
System.out.print(intAry[i] + " "); // should output "0 1 2 4 "
}
set
array_fav[1]=array_fav[2];
array_fav[2]=null;
You can do it using the following method..
public static String[] removeElements(String[] input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return result.toArray(input);
}
OR you could use ArrayUtils.
array = ArrayUtils.removeElement(array, element)
For simple arrays like this you can't do this in this way
here is the full sample code for this
int current_id = 2;
String[] arr_fav = { "1", "2", "3" };
for (int i = 0; i < arr_fav.length; i++) {
if (current_id == Integer.parseInt(arr_fav[i])) {
String[] arr_fav_tem = new String[arr_fav.length - 1];
arr_fav[1] = null;
int counter = 0;
for (int j = 0; j < arr_fav.length; j++) {
if (arr_fav[j] != null) {
arr_fav_tem[counter] = arr_fav[j];
counter++;
}
}
arr_fav = arr_fav_tem;
}
}
for (int i = 0; i < arr_fav.length; i++) {
System.out.println(arr_fav[i]);
}
String[] arr_fav =
{ "1", "2", "3" };
List<String> myList = Arrays.asList(arr_fav);
String currentId = String.valueOf(current_id);
for (int i = 0; i < arr_fav.length; i++)
{
if (arr_fav[i].equals(currentId))
{
myList.remove(i);
}
}
private String[] removeItem(String[] names,
int position) {
ArrayList<String> al_temp=new ArrayList<String>();// temporary ArrayList
for(int i=0;i<names.length;i++)
{
al_temp.add(names[i]);
}
al_temp.remove(position);
names= new String[al_temp.size()];//array cleared with new size
for(int i=0;i<al_temp.size();i++)
{
names[i]=al_temp.get(i);
}
return names;
}
Copy this method:
private static String[] deleteElement(String stringToDelete, String[] array) {
String[] result = new String[array.length];
int index = 0;
ArrayList<String> rm = new ArrayList<String>();
for(int i = 0; i < array.length; i++) {
rm.add(array[i]);
}
for(int i = 0; i < array.length; i++) {
if(array[i].equals(poistettava)) {
index = i;
}
}
rm.remove(index);
result = rm.toArray(new String[rm.size()]);
return result;
}
To delete element:
String[] array = {"1", "2", "3"};
array = deleteElement("3", array);

Categories

Resources