Duplication on ArrayList Java - java

my title is bad but I don't have an idea what it should be. My question is simple, I have four arraylist and I want to get similar words from two of them and put another arraylists. Anyway my array lists like;
arrList1 = {car, apple, many, car, tyty, man, superman};
arrList2 = {stack, vs, etc, vs, car, tyty, stack, tyty, many, car, apple};
I tried this;
for (int i = 0; i < arrList1.size(); i++) {
for (int j = 0; j < arrList2.size(); j++) {
if (arrList1.get(i).equals(arrList2.get(j))) {
arrList3.add(arrList1.get(i);
arrList4.add(arrList2.get(j);
}
}
But as you see arrList1 and arrList2 have duplicates so arrList4 will have same element more than normal. Also I have to count elements which are in arrList1 and arrList2 so I shouldn't use Set Collections. What should I do?

Try
ArrayList<String> temp = new ArrayList<String>();
boolean found = false;
for (int i = 0; i < arrList1.size(); i++) {
found = false;
for (int j = 0; j < arrList2.size(); j++) {
if (arrList1.get(i).equals(arrList2.get(j))) {
found = true;
if (!temp.contains(arrList2.get(j)) {
arrList4.add(arrList2.get(j));
}
}
}
if (found) {
arrList3.add(arrList1.get(i));
temp.add(arrList1.get(i));
}
}
This will check if the new ArrayList does not already contain the item.

Try this
ArrayList tempList=new ArrayList(arrList1);
tempList.removeAll(arrList2);
arrList4 = new ArrayList(arrList1);
arrList4.removeAll(tempList);

You should use another type of list but you can also make-do with an arraylist like so:
for (int i = 0; i < arrList1.size(); i++) {
for (int j = 0; j < arrList2.size(); j++) {
if (arrList1.get(i).equals(arrList2.get(j))) {
if(!(arrList3.contains(arrList1.get(i))) {
arrList3.add(arrList1.get(i);
}
if(!(arrList4.contains(arrList2.get(j))) {
arrList4.add(arrList2.get(j);
}
}
}
hope that helps.

Related

How do I copy a two dimensional array with null at the end?

[[4390, Apple, $1.59],[4046, Avocado, $0.59],null, null]
I am trying to copy the above two dimensional array with for loop, but I got:
[[4390, Apple, $1.59],[4046, Avocado, $0.59],[null, null, null],[null, null, null]
What should I do to get null instead of [null, null, null] without importing Array?
Following is my code. Assume the array I want to copy is called "marketItems"
int nullIndex = marketItems.length;
for(int j = 0; j < marketItems.length; ++j) {
if(marketItems[j] == null) {
nullIndex = j;
break;
}
}
String[][]copy = new String[marketItems.length][3];
for(int i = 0; i < nullIndex; ++i ) {
for(int j = 0; j < marketItems[i].length; ++j) {
copy[i][j] = marketItems[i][j];
}
}
for(int i = nullIndex; i < marketItems.length; ++i) {
marketItems[i] = null;
}
Well for practical code, you should be importing and using Arrays (or something) rather than implementing this by hand. But assuming that this is a learning exercise ...
The problem is this line:
String[][]copy = new String[marketItems.length][3];
This is explicitly allocating a rectangular 2-D array. But your requirement is for a ragged array where some of the first level subarrays are actually null.
This is a simpler, cleaner way of doing it:
String[][] copy = new String[marketItems.length][];
That allocates just the top-level array, with the sub-array references default initialized to null. Then you allocate sub-arrays as required for the non-null sub-arrays in the original marketItems object ... and populate them.
for (int i = 0; i < marketItems.length; i++) {
if (marketItems[i] != null) {
copy[i] = new String[marketItems[i].length];
for (int j = 0; j < marketItems[i].length; j++) {
copy[i][j] = marketItems[i][j];
}
}
}
(That is about half the number of lines of code in the original version. And it will be more efficient, and easier to understand for someone who can read Java.)
public class Test {
public static void main(String[] args) {
String[][] marketItems = new String[][]{
{"4390", "Apple"," $1.59"},{"4046", "Avocado", "$0.59"},null,null
};
int nullIndex = marketItems.length;
for(int j = 0; j < marketItems.length; ++j) {
if(marketItems[j] == null) {
nullIndex = j;
break;
}
}
String[][]copy = new String[marketItems.length][3];
for(int i = 0; i < nullIndex; ++i ) {
for(int j = 0; j < marketItems[i].length; ++j) {
copy[i][j] = marketItems[i][j];
}
}
for(int i = nullIndex; i < marketItems.length; ++i) {
// marketItems[i] = null;
copy[i]=null;
}
System.out.println(Arrays.deepToString(copy));
}
}

how to replace duplicate elements with a string in arrayList?

i want to replace duplicate element with "repeated" string for example,
the arraylist is ["a","b","b","c","a","c","a"], the new array is ["a","b","repeated","c","repeated","repeated","repeated]
i have tried this
ArrayList<String> m = new ArrayList();
m.add("a");
m.add("b");
m.add("b");
m.add("c");
m.add("a");
m.add("c");
m.add("a");
System.out.println(m);
for (int i = 0; i < m.size(); i++) {
for (int j = 0; j < m.size(); j++) {
if (m.get(i).equals(m.get(j))){
m.set(j, "repeated");
}
}
}
but it's not working
No need to two nested loop. just use a Set to store repeated string.
Set<String> repeat = new HashSet<>();
int index = -1;
for (String s:m){
index++;
m.set(index, repeat.add(s) ? s : "repeated");
}
Two errors:
You print your list before updating. Move the
System.println(...) after the loop.
You are replacing all elements (not just the duplicates) with the "repeated" String since
the first comparison in the loop is with the element
itself.
ArrayList<String> m = new ArrayList<>();
m.add("a");
m.add("b");
m.add("b");
m.add("c");
m.add("a");
m.add("c");
m.add("a");
for (int i = 0; i < m.size(); i++) {
for (int j = i + 1; j < m.size(); j++) {
if (m.get(i).equals(m.get(j))){
m.set(j, "repeated");
}
}
}
System.out.println(m);

Java changes multiple values at once

I really don't like asking these kinds of questions and this is probably a duplicate, but i am really stuck on this and because i am new to java (not to programming in general) i can't figure it out.
The problem is as follows: The array names should be sorted, and i came up with the following code:
String[] temp_names = names;
for (int i = 0; i < names.length; i++)
{
for (int j = 0; j < names.length; j++)
{
String biggest = ""+(0);
int biggest_index = 0;
for (int chr = 0; chr < ((biggest.length() < temp_names[j].length()) ? biggest.length() : temp_names[j].length()); chr++)
{
if (biggest.toCharArray()[chr] > temp_names[j].toCharArray()[chr])
{
break;
}
else if (biggest.toCharArray()[chr] < temp_names[j].toCharArray()[chr])
{
biggest = temp_names[j];
biggest_index = j;
break;
}
}
names[i] = biggest;
temp_names[biggest_index] = ""+(255);
}
}
The problem occurs at the last line. I set the value to as high as possible so when sorting it is basically ignored (it will always come last). The problem is that when temp_names[biggest_index] is set to '255', biggest is also set to 255 which in turn sets names[i] to 255. This leaves me with an array full of empty names.
I know this has something to do with that java copys the variable as a reference instead of as a value, but when i try to copy/clone it by using names[i] = new String(biggest) it still has the same result. I've tried many different things and now i've run out of ideas so i hope someone here can help.
Thanks in advance for any answers,
Harm
-Edit:
This is an exercise for school so i can't just use standard java functions.
class SOCLass {
public static void main(String[] args){
String[] names = new String[] {"joe", "bill"};
String[] temp_names = names;// new String[names.length];
//System.arraycopy(names, 0, temp_names, 0, 2);
for (int i = 0; i < names.length; i++)
{
for (int j = 0; j < names.length; j++)
{
String biggest = ""+(0);
int biggest_index = 0;
for (int chr = 0; chr < ((biggest.length() < temp_names[j].length()) ? biggest.length() : temp_names[j].length()); chr++)
{
if (biggest.toCharArray()[chr] > temp_names[j].toCharArray()[chr])
{
break;
}
else if (biggest.toCharArray()[chr] < temp_names[j].toCharArray()[chr])
{
biggest = temp_names[j];
biggest_index = j;
break;
}
}
names[i] = biggest;
temp_names[biggest_index] = ""+(255);
}
}
for(String s : names)
System.out.println(s);
for(String s : temp_names)
System.out.println(s);
}
}
This is the code as you wrote it. It prints out 255 on both. Comment in the new String[...] and System.arraycopy(...) and it prints bill the longest/biggest.
By not allocating a new array, temp_names and names are the same. Changes in one reflect on the other

How to fill an ArrayList<TextView> with data of another smaller List of Strings in Android

I have an ArrayList of TextViews of a fixed size X.
I want to set the text of the TextViews based on a smaller ArrayList of Strings.
The remaining ArrayList TextViews I want them to have e.g a dash
How I am going to accomplish this with following way?
for(int i = 0; i<TotalList.size();i++)
{
TotalList.get(i).setText(SmallerList.get(a).toString());
a++;
}
// iterate over smaller list
for(int i = 0; i < SmallerList.size(); i++) {
TotalList.get(i).setText(SmallerList.get(i));
}
// set remaining items
for (int i = SmallerList.size(); i < TotalList.size(); i++) {
TotalList.get(i).setText("---");
}
for(int i = 0; i < smallList.size(); i++) {
totalList.get(i).setText(smallList.get(i));
}
something like this ?
int size = smallerList.size();
for(int i = 0; i<TotalList.size();i++)
{
TextView tv=new TextView(getApplicationContext());
if(i <size){
tv.get(i).setText(SmallerList.get(i).toString());
}else{
tv.get(i).setText("-");
}
You can do something like this:
for(int i = 0; i<TotalList.size();i++){
if(i < SmallerList.size()){
TotalList.get(i).setText(SmallerList.get(i));
}else{
TotalList.get(i).setText("...");
}
}
Use two for loops :
for(int i = 0; i<SmallerList.size();i++)
{
TotalList.get(i).setText(SmallerList.get(i).toString());
}
for(int i = SmallerList.size(); i<TotalList.size();i++)
{
TotalList.get(i).setText("----------");
}

Finding duplicate INT in 2D array

I'm stuck on this method.
public class Duplicate{
public static boolean extra(int [][] grid)
{
for(int i = 0; i < grid.length; i++)
for(int j = 0; j < grid[i].length-1; j++)
if(grid[i][j] == grid[i][j+1])
{
System.out.println(grid[i][j]);
return true;
}
return false;
}
public static void main(String[] args){
int [][] grades = {{3,5,8,7},
{2,1,11,4},
{13,20,10,6},
{7,0,12,15}
};
System.out.print(extra(grades));
}
}
I want to find if there are any duplicated ints in the array. return true if there is and the int that is duplicated. My method keeps coming out FALSE. what am I doing wrong? Any help would be appreciated. Please and thank you.
All your method is doing is checking if two consecutive elements are equal, which does not tell you anything about duplicates that are not adjacent. One way to do this would be to have a Map<Integer, Integer> that maps the values to their frequencies:
Map<Integer, Integer> map = new HashMap<>();
for (int[] row : grid) {
for (int a : row) {
map.put(a, map.containsKey(a) ? map.get(a) + 1 : 1);
}
}
You can then loop over the entries of this map to find the elements with a frequency greater than or equal to 2.
To rewrite your method so it works:
ArrayList<Integer> comeBefore = new ArrayList<Integer>();
for(int i = 0; i < grid.length; i++) {
for(int j = 0; j < grid[i].length; j++) {
if(comeBefore.contains(grid[i][j])) {
System.out.println(grid[i][j]);
return true;
}
comeBefore.add(grid[i][j]);
}
}
return false;
I don't have time to think about it right now... but maybe a set or such would be a more efficient data structure to use for this. Also this code may not be right... but it's the gist of it; it's untested.
private static boolean extra(int[][] data) {
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (set.contains(data[i][j])) {
return true;
} else {
set.add(data[i][j]);
}
}
}
return false;
}
You are only comparing adjacent numbers in your loop with this line if(grid[i][j] == grid[i][j+1])
Like arshajii mentioned using a Map will is one way to do this. If you want to keep the co-ordinates of each duplicate then you could extend arshajii's answer to have a Map of Lists like so.
Map<Integer, List<Point>> map = new HashMap<>();
for(int i = 0; i < grid.length; i++)
{
for(int j = 0; j < grid[i].length; j++)
{
int val = grid[i][j];
if(map.containskey(val))
map.put(val, map.get(val).add(new Point(i,j));
else
{
List<Point> li = new ArrayList<>();
li.add(new Point(i,j));
map.put(val, li);
}
}
}
Then to get duplicates you find any key that has a size > 1 and you can get the co-ordinates
for(Integer key : map.ketSet())
{
List<Point> li = map.get(key);
if(li.size() > 1)
{
System.out.println("The value " + key +" was duplicated at the indices: ");
for(Point p : li)
System.out.println(p.x + ", " + p.y);
}
}
But this is probably over the top!

Categories

Resources