Reputation: 796
I have a java class which involves a String array and two for loops
for going through the array elements and prints them plus their redundancy in the
array as they are Strings .
I want someone help me to print each element (String) one time only even it
repeated in the array.
The following code prints some element in the array more than one time.
So comparison between elements of the array Needed
public class myClassName {
static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};
public static String [] getArray()
{
String str[] = new String[myArray.length];
for(int i=0;i<myArray.length;i++)
{
str[i] = myArray[i].toString();
}
return str;
}
public static void main( String [] args)
{
String d [] = getArray();
int noOftimesRepeated;
for(int i=0;i<getArray().length;i++)
{
noOftimesRepeated=1;
String currentName = d[i];
for(int j=0;j<getArray().length;j++)
{
if(i!=j && d[i].equalsIgnoreCase(d[j]))
{
noOftimesRepeated = noOftimesRepeated+1;
}
}
int j =0;
System.out.println(d[i]+"\t" +"\t"+noOftimesRepeated);
}
}
}
Please Is there any solution without using .util.* package
I have a second trial but it out prints the one element and it redundancy
only.
public class Javafool {
static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khalo","Valderama"};
static String str2[] = new String[myArray.length];
public static String [] getArray()
{
String str[] = new String[myArray.length];
for(int i=0;i<myArray.length;i++)
{
str[i] = myArray[i].toString();
}
return str;
}
public static void main(String[] args) {
String d [] = getArray();
int noOftimesRepeated;
sort(myArray);
int no_of_repeat=1;
String temp =null;
int i ;
for( i = 0;i<myArray.length-1;i++)
{
temp = myArray[i];
myArray[i] = myArray[i+1];
myArray[i+1] = temp;
if(myArray[i].equals(temp))
{
no_of_repeat= ++no_of_repeat;
}
}
System.out.println(myArray[i]+""+temp+"\t"+"\t\t"+no_of_repeat);
}
public static void sort(String [] array) {
String temp = null;
for(int j=0;j<array.length;j++)
{
for(int i = 0; i<array.length-1;i++)
{
if(array[i].compareTo(array[i+1])<0)
{
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}}}}
Upvotes: 4
Views: 10891
Reputation: 145
The problem is that arrays are fixed size in memory and you can't drop the duplicated values from the array.
So either you transfer the duplicated values to unwanted values (like zeros or any string), or you use an ArrayList
, which allows you to drop values from the list (because lists are not fixed size and you can change it).
Upvotes: 0
Reputation: 796
I found the solution,(The following solution doesn't involve java.util
package , and it depends on Quicksort Algorithm).
Thank you all.
public class Javafool
{
static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khalo","Valderama","Daoud"};
static String str2[] = new String[myArray.length];
public static void main(String[] args)
{
int [] noOftimesRepeated;
sort(myArray);
int no_of_repeat=1;
String temp =null;
int i ;
int count = 0;
String previous = null;
for (String s : myArray)
{
if (s.equals(previous))
{
count++;
}
else
{
if( previous !=null)
System.out.println(previous + " :" + count);
previous = s;
count = 1;
}
}
if (myArray.length > 0)
{
System.out.println(previous + " :" + count);
}
}
public static void sort(String [] array) {
String temp = null;
for(int j=0;j<array.length;j++)
{
for(int i = 0; i<array.length-1;i++)
{
if(array[i].compareTo(array[i+1])<0)
{
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
} } }
Upvotes: 0
Reputation: 781
You dun need 2 for loop to do it. Just this 3 line of code will do! :D
final List<String> lst = Arrays.asList("Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled");
final Set<String> set = new HashSet<String>(lst);
System.out.printf("Unique values: ", set);
If without *ulit package
You will need a custom sort method. The pseudo code can goes like that (Not a efficient way of doing)
"Given" lst array;
Array temp = new Araay(lst.lenght);
//two for loop for
(int i = 0; i< lst.lenght; i++) {
if(i==0){
temp[i] = lst[i]; // first array
}
for (int u = 0 ; u < lst.lenght; u ++){
//Write a code here if the lst[i] string is not equal to any temp[u] string, add then inside. Else dun care :) Cheers!
}
}
Upvotes: 0
Reputation: 18702
Aside from using Set, you can also create a list of unique items.
String [] myArray = {"Khaled", "Valderama", "Daoud", "Khaled", "Rasheed", "Daoud", "Valderama", "Khaled"};
List<String> myPrintList = new ArrayList<String>();
for(String str : myArray){
if(!myPrintList.contains(str)){ // Check first if myPrintList contains the item already
myPrintList.add(str); // Add if the list doesn't contain that item
}
}
// Print list
for(String str : myPrintList){
System.out.println(str);
}
EDIT based from comment:
Not sure why you do not want to use util package, but-
String [] myArray = {"Khaled", "Valderama", "Daoud", "Khaled", "Rasheed", "Daoud", "Valderama", "Khaled"};
StringBuilder uniqueNames = new StringBuilder(); // For storing all unique names separated by a pipe (|)
for(String str : myArray){
if(uniqueNames.indexOf(str) < 0){ // Check if str exists in builder yet
uniqueNames.append(str); // Add str if it doesn't exist
uniqueNames.append("|"); // Add delimiter
}
}
String[] myPrintArray = uniqueNames.toString().split("\\|"); // Get an array by splitting using the pipe delimiter
for(String str : myPrintArray){
System.out.println(str);
}
Upvotes: 0
Reputation: 525
I agree with previous guy, firstly you should make you arraylist in a sequence, you can try the Quicksort algorithm,secondly you should compare current element with the previous one, if they equal, do not print it. it is easy, right?
you can extract your quicksort algorithm function to a util class, so you can use it in later development.
Upvotes: 0
Reputation: 31225
If you absolutely don't want to use java.util, you can still sort by hand and remove adjacent duplicates :
public static void main(String[] args) {
String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};
sort(myArray);
String last=null;
for(int i = 0;i<myArray.length;i++) {
if(last==null || !myArray[i].equals(last)) {
last = myArray[i];
System.out.print(last+", ");
}
}
}
/*
* Very naive method to sort elements. You can improve this with a merge sort.
* Arrays.sort() would do the same job in a better way.
*/
public static void sort(String [] array) {
String temp = null;
for(int j=0;j<array.length;j++) {
for(int i = 0; i<array.length-1;i++) {
if(array[i].compareTo(array[i+1])<0) {
temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
}
}
Upvotes: 1
Reputation: 35557
You can use set
. Set
will avoid adding duplicates.
String [] myArray = {"Khaled","Valderama","Daoud",
"Khaled","Rasheed","Daoud","Valderama","Khaled"};
Set<String> set=new HashSet<>();
for(String i:myArray){
set.add(i);
}
System.out.println(set);
If you don't want to use java.util.*
package try following way.
String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud",
"Valderama","Khaled"};
String[] newArr=new String[myArray.length];
int j=0;
for(String i:myArray){
if(!Arrays.toString(newArr).contains(i)){
newArr[j]=i;
j++;
}
}
Upvotes: 0
Reputation: 7225
Use Map<String, Integer>
, String for the input string, Integer for the noOftimesRepeated
counter.
Example:
Map<String , Integer> map = new HashMap<String , Integer>();
// Add and count str Repeated times.
map.put(str, map.get(str) + 1);
// output string and counter pair in map
System.out.println(map);
Upvotes: 2
Reputation: 5531
try this. The for Loop will not be running fully for duplicate items
import java.util.ArrayList;
public class myClassName {
static String [] myArray = {"Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled"};
public static String [] getArray()
{
String str[] = new String[myArray.length];
for(int i=0;i<myArray.length;i++)
{
str[i] = myArray[i].toString();
}
return str;
}
public static void main( String [] args)
{
String d [] = getArray();
int noOftimesRepeated;
ArrayList<String> list = new ArrayList<String>();
for(int i=0;i<getArray().length;i++)
{
if(list.contains(d[i]))
continue;
noOftimesRepeated=1;
for(int j=0;j<getArray().length;j++)
{
if(i!=j && d[i].equalsIgnoreCase(d[j]) )
{
noOftimesRepeated = noOftimesRepeated+1;
list.add(d[i]);
}
}
System.out.println(d[i]+"\t" +"\t"+noOftimesRepeated);
}
}
}
Upvotes: 0
Reputation: 12924
You can do as below,
String[] myArray = { "Khaled", "Valderama", "Daoud", "Khaled",
"Rasheed", "Daoud", "Valderama", "Khaled" };
Set<String> sets = new HashSet<String>(Arrays.asList(myArray));
System.out.println(Arrays.toString(sets.toArray()));
Upvotes: 0
Reputation: 9232
Add the Strings to Set<String>
, which eliminates duplicate values, and then print them:
List<String> list = Arrays.asList("Khaled", "Valderama",...);
Set<String> set = new LinkedHashSet<String>(list);
for(String s : set)
System.out.println(s);
Upvotes: 3
Reputation: 77904
public static void main(String[] args) {
List<String> myArray = Arrays.asList("Khaled","Valderama","Daoud","Khaled","Rasheed","Daoud","Valderama","Khaled");
Set<String> sets = new HashSet<String>();
sets.addAll(myArray);
System.out.println(sets);
}
Output: [Khaled, Valderama, Rasheed, Daoud]
Upvotes: 0