I have some problem with my Java code. I'm supposed to use loops and not any other method.
Say that my ArrayList contains of
[Dog Cat Dog Dog Cat Dog Horse]
My goal is also to remove the copies of Dog and Cat so my final results equals
[Dog Cat Horse]
public void removeDouble(){
int counter = 0;
for (int i = 0 ; i < animals.size(); i++) {
for (int j = 1+i; j < animals.size() ; j++)
//don't start on the same word or you'll eliminate it.
if ( animals.get(j).equals( animals.get(i) ) ) {
animals.remove(animals.get(j));
counter++;
}
}
}
It feels like the "logic" is correct but my code does not work very well. Can somebody help me a little?
You can do like this.
ArrayList<String>list=new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("A");
System.out.println("Before "+list); // output[A,B,C,A]
Set<String> listWithoutDuplicates = new LinkedHashSet<String>(list);
list.clear();
list.addAll(listWithoutDuplicates);
System.out.println("list without duplicates : " + list);// output[A,B,C]
The logic for the inner loop is incorrect.
You will skip items every time you have the same item appear consecutively in the list.
Say you had "dog", "dog", "dog", "cat". When you remove the "dog" at index 1, the list now becomes "dog", "dog", "cat".
The problem is that your "j" index is now incremented to 2 so the next test will access the "cat" item, not the "dog" item. So every time you remove an item you are skipping the next item in the list which is why you get inconsistent results.
The solution is to either:
decrement the j variable every time you remove an item
start the inner loop from the end of the list and count down backwards toward 0.
It would be simpler to start from the end of the list and decrement the counter. After removing the double at i, we can break without checking the whole string, because further doubles will be detected when i reaches j.
for(int i=animals.size()-1; i>0; i--) {
for(int j=i-1; j>=0; j--) {
if(animals.get(i).equals(animals.get(j))) {
animals.remove(i);
break;
}
}
}
Moving backwards avoids the problem as you move forward the indexes have changed because you removed earlier elements (and you failed to adjust the index to take that into account).
Another problem with your logic you were using remove(object) rather than remove(index), which causes the first matching object to be removed. However, based on expected output, you want to preserve the order of the first matching objects. So instead you should have removed the last matching object, via index.
If you want to move forward rather than backwards, but you don't wish to make adjustments to the index after a removal, it is possible to make use of iterator's remove method:
for(int i=0; i<animals.size()-1; i++) {
ListIterator<?> iter = animals.listIterator(i+1);
while(iter.hasNext()) {
if(animals.get(i).equals(iter.next())) {
iter.remove();
}
}
}
Unfortunately the outer loop here cannot use an iterator because that would result in a ConcurrentModificationException.
Finally, you could also use a subList to solve it with a single explicit loop:
for(int i=0; i<animals.size()-1; i++) {
animals.subList(i+1, animals.size()).removeIf(animals.get(i)::equals);
}
In Java 8 we can use Stream API to remove duplicates, Like below snippet.
List<String> uniqueAnimal = animal.stream().distinct().collect(Collectors.toList());
Working Example.
import java.util.*;
import java.util.stream.Collectors;
public class MyClass {
public static void main(String args[]) {
List<String> animal = new ArrayList<>();
animal.add("Dog");
animal.add("Cat");
animal.add("Dog");
animal.add("Dog");
animal.add("Cat");
animal.add("Dog");
animal.add("Horse");
List<String> uniqueAnimal = animal.stream().distinct().collect(Collectors.toList());
System.out.println("animal => " + animal);
System.out.println("uniqueAnimal => " + uniqueAnimal);
}
}
With Java 8 stream you can do as follows:
public class RemoveDuplicates {
public static void main(String[] args) {
removeDuplicateElements(Arrays.asList("Dog","Cat","Dog","Dog","Cat","Dog","Horse"));
}
private static void removeDuplicateElements(List<String> animalList)
{
animalList.stream().distinct().collect(Collectors.toList()).forEach(System.out::println);
}
}
Your removing the items as you are iterating over them, have an array that holds indexes, and when you find a double, add the index to the indexes array. Iterate over the indexes array and delete from the animals arraylist.
Your current code -
for (int i = 0; i < animals.size(); i++) {
for (int j = 1 + i; j < animals.size(); j++)
if (animals.get(j).equals(animals.get(i))) {
animals.remove(animals.get(j)); // this would remove the current element only if the previous element is same as the current element
// since the index `j` would change post that
}
}
}
A simple way to do this is
animals.stream().distinct().collect(Collectors.toList()).forEach(System.out::print);
Or using -
Set<String> distAnimal = new HashSet<>(animals);
System.out.println(Arrays.toString(distAnimal.toArray()));
Thanks for all the answers. I still have a few problems, this is what i have came up with:
int counter =0;
for(int i = 0 ; i < animals.size() ; i++){
for(int j = animals.size() -1 ; j>i ; j--){
if(animals.get(j).equals(animals.get(i))){
counter++;
}
}
}
System.out.println(counter);
}
So now I'm starting the inner loop from the end of the ArrayList. Priority right now is only the get the loop working and then add remove etc.
Cheers!
Related
List<List<Integer>> myList = new ArrayList<>(3);
for(int i=0; i < 3; i++) {
myList.add(new ArrayList());
}
myList.get(0).add(1); // 0,0
myList.get(0).add(4); //0,1
myList.get(1).add(2); // 1,0
myList.get(1).add(5); // 1,1
myList.get(2).add(3);// 2,0
myList.get(2).add(6); //2,1
myList.get(2).add(7); //2,3
for(int i =0; i<myList.get(i).size(); i++){
for(int j=0; j<myList.size(); j++){
System.out.println(myList.get(j).get(i));
}
}
I cant figure out how to iterate through the list on a index based, with different lengths on each list. My code above only works if all lists are the same size.
Ideal output would be:
1
2
3
4
5
6
7
But I cant figure out how to print out 7 since that list is a different length. This might be a very simple solution and ill probably feel dumb after. Thanks guys
To iterate over all elements of List of Lists you need to iterate in the first for-loop over the outer List, and in the second for-loop over the inner loop at that index. There are several possibilities to achieve the iteration over all elements, as you will see in the following examples.
(Your code would also produce a IndexOutOfBoundsException for the last entry).
Iterating through a List of Lists
Option 1 (your code corrected)
for (int i = 0; i < myList.size(); i++) { // i represents index of outer List
for (int j = 0; j < myList.get(i).size(); j++) { //j represents index of the inner list at index i
System.out.println(myList.get(i).get(j));
}
}
Option 2 (using for-each loop)
for (List<Integer> innerList : myList) {
for (Integer currentPosition : innerList) {
System.out.println(currentPosition);
}
}
Option 3 (using streams)
myList.stream()
.flatMap(Collection::stream)
.forEach(System.out::println);
}
Edit due to comment: added traverse method for wanted output
If you want to print out all first entries of the inner lists first, a possibility would be to traverse your List<List<Integer>> with a method like this (method is generic, would also work with other classes):
private static <T> List<List<T>> traverse(List<List<T>> input) {
List<List<T>> result = new ArrayList<>();
for (int i = 0; i < input.size(); i++) {
for (int j = 0; j < input.get(i).size(); j++) {
if(result.size() <= j) {
result.add(new ArrayList<>());
}
result.get(j).add(input.get(i).get(j));
}
}
return result;
}
In your method then just create a new List<List<Integer>> like this and iterate over this new list of lists:
List<List<Integer>> myListTraversed = traverse(myList);
I need to merge two lists into one, in ascending order, not duplicates, and I think my code is really close, I'm just missing something and I can't figure it out. As of now, my code is not working properly in my merge method. I think it has something to do with my loops, but I just can't work around it. My current method prints the new list, but it is not in perfect increasing order. I would appreciate any assistance in figuring out how to make this method print my merged list with ascending order using the contents of l1 and l2.
**Note: I cannot use any built-in array sorting methods.
Thanks!
import java.util.ArrayList;
import java.util.Random;
public class MergeLists {
public static ArrayList<Integer> merge(ArrayList<Integer> l1, ArrayList<Integer> l2){
ArrayList<Integer> mergedList = new ArrayList();
for (int j = 0; j < l1.size(); j++) {
if (l1.get(j) < l2.get(j)) {
mergedList.add(l1.get(j));
mergedList.add(l2.get(j));
} else {
mergedList.add(l2.get(j));
mergedList.add(l1.get(j));
}
}
for (int i = l2.size() - l1.size(); i < l2.size(); i++) {
mergedList.add(l2.get(i));
}
return mergedList;
}
public static ArrayList<Integer> makeRandomIncreasingList(int length) {
ArrayList<Integer> randomList = new ArrayList();
Random rand = new Random();
int inList = rand.nextInt(9) + 1;
int inList2 = rand.nextInt(9) + 1;
for (int i = 0; i < length; i++) {
randomList.add(inList);
inList = inList + inList2;
}
return randomList;
}
public static void doMergeTest() {
ArrayList<Integer> list1 = makeRandomIncreasingList(10);
ArrayList<Integer> list2 = makeRandomIncreasingList(20);
ArrayList<Integer> mergedList = merge(list1, list2);
System.out.println("List 1:" + list1);
System.out.println("List 2:" + list2);
System.out.println("Merged list:" + mergedList);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
System.out.println("Performing merge test #" + (i + 1) + ":");
doMergeTest();
}
}
}
Remove duplicates
arrayList1.remove(arrayList2);
Then merge two arrayList:
arrayList1.addAll(arrayList2);
And Lastly sort the last
collections.sort(arrayList1);
Another way is to use SET: Set doesnt allow duplicates
(HashSet is faster depending on the List implementation class)
Set setmerge = new HashSet(list1);
setmerge.addAll(list2);
list1.clear();
list1.addAll(setmerge);
The first part of your merge() method seems ok, if you modify it a little bit. You need to be going through both lists in parallel, something like
int i = 0, j = 0;
for (; i < l1.size() && j < l2.size();)
And compare individual items and increment indices independently, as in
if (l1.get(i) < l2.get(j)) {
...
i++;
} else
...
j++;
}
The way you were doing it you were literally going in parallel, which is not always correct (think of lists [1 2 2] and [1 1 1] => your merge would look like [1 1 1 2 1 2])
Then, after your "parallel" for-loop (the one where you're iterating through both lists), one of your indices is always going to break your loop because it's at the end of its list. For in-order merging, I usually declare i, j outside the loop (you'll need then after your first for-loop, like above) and then do something like (in your notation):
for (int i1 = i; i1 < l1.size(); i1++) {
mergeList.add(l1.get(i1));
}
for (int i2 = j; i2 < l2.size(); i2++) {
mergeList.add(l2.get(i2));
}
After your first for-loop, you get to the end of exactly one of the lists (someone's going to break the loop), so exactly one of the above loops is going to get executed, and that will contain the remaining items, in order.
Edit: your last for-loop of the merge() method is not correct for your purpose.
You have assumed l2 items are always bigger than l1 items, since you are adding remainder of l2 items in the end of the list. You need to compare them with mergedList items and add them accordingly.
I am having problems with making a method that will return distinct integers of the array list. I really want to do it with removing the duplicates and then just display the array list. I cannot figure out what is the problem. When I test it out this is the output I get: [3, 11, 33, 10]
This is my code
package getUniques;
import java.util.ArrayList;
public class Uniques {
public static ArrayList<Integer> getUniques( ArrayList<Integer> list ){
int i = 0;
while(i < list.size() - 1){
for (int j = 0; j < list.size(); j++){
if (list.get(i) == list.get(j))
list.remove(i);
}
i++;
}
return list;
}
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(3);
list.add(5);
list.add(11);
list.add(22);
list.add(33);
list.add(22);
list.add(10);
System.out.println(getUniques(list));
}
}
You can also get unique values by using Set. Insert the values in a Set and then put it back into an ArrayList like new ArrayList(theSet);
Changing the list as you iterate over it is always going to cause pain!
Say you remove item 3 (so the old 4th becomes the new 3) - then you do i++, so you are effectively skipping the "old 4th" element.
You can skip the i++ if you removed the item to get back on track, but a some other
solutions:
Use a Set or similar in the first place so you can't get duplicates.
Use a second list to hold the values (or indexes) of items you want
to remove (if using indexes, you can remove them highest to lowest
else you end up with the same issue: delete index 1, index 4 is now
index 3...)
Flip your search so you are going back towards 0, same principal
applies. You can remove high indexes without impacting lower ones.
Make your outer loop use an iterator so you can use the remove operation.
Your code has a few problems. Here's fixes for your existing code:
First you are removing the wrong index. You've identified the element at j as the duplicate; remove it instead of the element at i.
list.remove(j); // j not i
Next, you are removing all elements that are the same, and you aren't leaving the "original". To fix this, only test (and remove) those that are past i in the loop.
for (int j = i + 1; j < list.size(); j++){ // Start at i + 1, not 0.
Then you'll need to retry your j index once you've removed it, because the rest of the elements have been shifted backwards 1 spot. Instead of
if (list.get(i) == list.get(j))
list.remove(i);
Try
if (list.get(i) == list.get(j))
{
list.remove(j);
j--; // Try this j again next loop, once it's incremented again.
}
To remove items while iterating, you have to use an iterator, as it guarantees the order:
Iterator<Integer> iterator = list.iterator();
int i = 0;
List<Integer> listCopy = new ArrayList<Integer>(list);
while(iterator.hasNext()){
i++;
Integer value = iterator.next()
for (int j = i; j < listCopy.size(); j++){
if (value.equals(listCopy.get(j))) {
iterator.remove();
}
}
}
However, in this case, as you need to iterate twice through the same list, it's not the best solution. It might be faster putting everything into a sorted Set, as Set removes duplicates on its own.
please help me with this. i want to scan array1 through elements of array2 and disregard the elements of array2 if it's found in array1. so a list of fruits will only be left. but the output shows : ball, pencil. where i would want it to display only the elements in fruits. thanks for your help
import java.util.*;
public class CountFruits
{
public static void main(String args[])throws Exception
{
String array1[] = {"apple", "mango", "orange", "banana", "ball", "pencil"};
String array2[] = {"ball", "pencil"};
List<String> fruits = new ArrayList<String>();
for(int x = 0; x < array1.length; x++)
{
for(int y = 0; y < array2.length; y++)
{
if(array1[x].equals(array2[y]))
{
System.out.println(array1[x] + "\t" + array2[y]);
if(!fruits.contains(array1[x]))
{
fruits.add(array1[x]);
}
}
}//end for
}//end for
System.out.println("fruits: " +fruits);
}
}
First, I am assuming that this is a homework of sorts, so I wouldn't spoil your exercise by fixing your code.
Here is the idea: you need to create a boolean variable that indicates if the nested loop has found anything or not, set it to "not found" going into the loop, and checking it after the loop. If the loop indicates that an item has been found, skip it; otherwise, add it. Remember, you can do it only after the nested loop has finished, so calling fruits.add inside the nested loop is premature.
boolean found = false;
for(int y = 0; !found && y < array2.length; y++) {
found |= array1[x].equals(array2[y]);
}
if (!found) ...
You need to add the array1[x] to your list if it is NOT in array2[x]:
if (array1[x].equals(array2[y])) {
System.out.println(array1[x] + "\t" + array2[y]);
} else {
fruits.add(array1[x]);
}
But you will have duplicates. You can add a condition if(!fruits.contains(...)) before adding.
You could simplify your code by using the following algorithm:
add all the items in array1 to a list
remove the items in array2 from the list
The if statement if(array1[x].equals(array2[y])) will only be true for ball and pencil, so the fruit array will only add ball and pencil.
You could set the fruit array to hold all of array1 and then, if your if statement is true, remove that element from fruit the array.
or, you could set a boolean isFruit = true (in the outer for loop).
Then, if your if statement if(array1[x].equals(array2[y])) passes, set isFruit to false.
After the iteration of the inner loop, if isFruit is true, add it to the fruit array.
for(int x = 0; x < array1.length; x++)
{
boolean isFruit = true;
for(int y = 0; y < array2.length; y++)
{
if(array1[x].equals(array2[y]))
{
System.out.println(array1[x] + "\t" + array2[y]);
isFruit = false;
}
if(isFruit)
{
fruits.add(array1[x]);
}
}//end for loop
}//end for loop
The best approach would be, if you are using an IDE, step through the code, see where the logic fails. If you are not using a debugger, then put some System.out.println statements into the code. Then you can determine where the logic fails.
The other solution is to attempt the first solution I gave. That is, have the fruit array hold all of array1 and then remove elements that are found in array2
There are two flaws in your logic
1)Here You are adding the elements which should not be added in fruits list.
So you will have to check the elements which are not part of array2 and those should be added.So you may write that logic in else part.
2)You are checking each time whether the element already present in fruits list,instead of that use Set.It will disallow duplicate entries
I have an arraylist populated by four elements, the order of which is random (they are put here by random from another arraylist). I then have a for loop that repeats 10 times, at the end of each repetition I use the clear methods to clear all the elements of the arraylist. However, when I start a new repetition, I would like to repopulate my arraylist with the old (previously worked with) elements that were members of the list in the previous repetition, so that I can use the elements again. And I would like to repeat that until I get out of my 10-repetition for loop. Is there any way to achieve this at all?
Code in addition to my question:
ArrayList<String> answerPegs = new ArrayList<String>();
// add element to ArrayList
ArrayList<String> mySecretAnswer = new ArrayList<String>();
for (int n = 4; n > 0; n--)
{
//populate mySecretAnswer with elements from answerPegs
}
ArrayList<String> clone1 = mySecretAnswer;
for (int q = 0; q < 10; q++) {
for (o = 0; o < 4; o++)
{
}
// called clear() method here
} // END OF 10-ROW LOOP
I would suggest simply having 2 lists - keep a pristine copy of the original list, and then iterate over + clear a copy of that list.
public void doRepetitions(List<Object> original)
{
for( int i=0; i<10; i++ )
{
List<Object> working = new ArrayList<Object>( original );
doStuffWithList(working);
}
}
Edit:
Since you've posted your code, I can give a more specific answer:
You can change your clone to be:
ArrayList<String> clone1 = new ArrayList<String>(mySecretAnswer);
And then move that to be inside your for loop:
for (int q = 0; q < 10; q++)
{
ArrayList<String> clone1 = new ArrayList<String>(mySecretAnswer);
// ....
}
Could you use 2 loops nested and just have the inner loop be the for loop 10 times then clear once at the end