#comparing two arraylist, while ignoring order

1 messages ยท Page 1 of 1 (latest)

gritty slateBOT
#

<@&987246399047479336> please have a look, thanks.

#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

#

Here is an AI assisted attempt to answer your question ๐Ÿค–. Maybe it helps! In any case, a human is on the way ๐Ÿ‘. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

Here is an example of how you can compare two ArrayLists while ignoring the order using JUnit:

#
import org.junit.Assert;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ArrayListComparisonTest {

    @Test
    public void testArrayListComparison() {
        List<String> expectedList = new ArrayList<>();
        expectedList.add("Apple");
        expectedList.add("Banana");
        expectedList.add("Orange");

        List<String> actualList = new ArrayList<>();
        actualList.add("Banana");
        actualList.add("Orange");
        actualList.add("Apple");

        Assert.assertTrue(compareArrayLists(expectedList, actualList));
    }

    private boolean compareArrayLists(List<String> expected, List<String> actual) {
        if (expected.size() != actual.size()) {
            return false;
        }

        Map<String, Integer> map = new HashMap<>();

        for (String element : expected) {
            map.put(element, map.getOrDefault(element, 0) + 1);
        }

        for (String element : actual) {
            if (!map.containsKey(element)) {
                return false;
            }
            map.put(element, map.get(element) - 1);
            if (map.get(element) == 0) {
                map.remove(element);
            }
        }

        return true;
    }
}
#

In this example, we have two ArrayLists: expectedList and actualList. We want to compare these two lists while ignoring the order of elements.

The compareArrayLists method takes in the two lists as parameters. It first checks if the sizes of the lists are different. If they are different, it returns false.

Then, it creates a HashMap called map to store the elements of the expected list as keys and their occurrences as values.

Next, it iterates through the expected list and updates the occurrences in the map.

After that, it iterates through the actual list and checks if each element exists in the map. If an element doesn't exist, it returns false. If it exists, it decreases its occurrence in the map. If the occurrence becomes zero, it removes the element from the map.

Finally, if all elements are successfully matched and removed from the map, it means that both lists contain the same elements (ignoring order), and it returns true.

In the JUnit test method, we call this compareArrayLists method and assert that it returns true to ensure that both lists are equal (ignoring order).

mint patio
#

yeah posting your code here, formatted as the bot message shows
otherwise you can simply upload your file and our bot will take care of it

exotic barn
#

okay

mint patio
#

couldnt you just sort both lists into temporary lists and then compare them?

exotic barn
#

@Test
public void testTwoMovie(){
String filename = "data/testMovies.csv";
ArrayList<Movie> Reader = FileReader.readMovies(filename);
HashMap<String, ArrayList<Movie>> actual = new HashMap<>();
actual.put("Toy Story", Reader);
actual.put("Jumanji", Reader);

    ArrayList<String> ToyStoryCast = new ArrayList<>();
    ToyStoryCast.add("Tom Hanks");
    ToyStoryCast.add("Tim Allen");
    Movie ToyStory = new Movie("Toy Story", ToyStoryCast);

    ArrayList<String> JumanjiCast = new ArrayList<>();
    JumanjiCast.add("Robin Williams");
    JumanjiCast.add("Jonathan Hyde");
    Movie Jumanji = new Movie("Jumanji", JumanjiCast);

    ArrayList<Movie> Array = new ArrayList<>();
    Array.add(Jumanji);
    Array.add(ToyStory);

    HashMap<String, ArrayList<Movie>> expected = new HashMap<>();
    expected.put("Jumanji", Array);
    expected.put("Toy Story", Array);


    compareArrayList(expected, actual);

}

private void compareHelper(Movie expected, Movie actual){
    assertEquals(expected.getTitle(), actual.getTitle());
    assertEquals(expected.getCast(), actual.getCast());
}

private void compareArrayList(HashMap<String, ArrayList<Movie>> expected, HashMap<String, ArrayList<Movie>> actual){
    assertEquals(expected.size(), actual.size());
    for (String title : expected.keySet()){

        assertTrue(actual.containsKey(title));
        ArrayList<Movie> expectedtitle = expected.get(title);
        ArrayList<Movie> actualtitle = actual.get(title);
        assertEquals(expectedtitle.size(), actualtitle.size());
        for (int i = 0; i < expectedtitle.size(); i++){
            compareHelper(expectedtitle.get(i), actualtitle.get(i));
        }
    }
}
#

my filereader method returns an arraylist of the movie title and an arraylist of the cast

hardy crag
mint patio
#

pls use this when posting code

exotic barn
#
@Test
    public void testTwoMovie(){
        String filename = "data/testMovies.csv";
        ArrayList<Movie> Reader = FileReader.readMovies(filename);
        HashMap<String, ArrayList<Movie>> actual = new HashMap<>();
        actual.put("Toy Story", Reader);
        actual.put("Jumanji", Reader);

        ArrayList<String> ToyStoryCast = new ArrayList<>();
        ToyStoryCast.add("Tom Hanks");
        ToyStoryCast.add("Tim Allen");
        Movie ToyStory = new Movie("Toy Story", ToyStoryCast);

        ArrayList<String> JumanjiCast = new ArrayList<>();
        JumanjiCast.add("Robin Williams");
        JumanjiCast.add("Jonathan Hyde");
        Movie Jumanji = new Movie("Jumanji", JumanjiCast);

        ArrayList<Movie> Array = new ArrayList<>();
        Array.add(Jumanji);
        Array.add(ToyStory);

        HashMap<String, ArrayList<Movie>> expected = new HashMap<>();
        expected.put("Jumanji", Array);
        expected.put("Toy Story", Array);


        compareArrayList(expected, actual);

    }

    private void compareHelper(Movie expected, Movie actual){
        assertEquals(expected.getTitle(), actual.getTitle());
        assertEquals(expected.getCast(), actual.getCast());
    }

    private void compareArrayList(HashMap<String, ArrayList<Movie>> expected, HashMap<String, ArrayList<Movie>> actual){
        assertEquals(expected.size(), actual.size());
        for (String title : expected.keySet()){

            assertTrue(actual.containsKey(title));
            ArrayList<Movie> expectedtitle = expected.get(title);
            ArrayList<Movie> actualtitle = actual.get(title);
            assertEquals(expectedtitle.size(), actualtitle.size());
            for (int i = 0; i < expectedtitle.size(); i++){
                compareHelper(expectedtitle.get(i), actualtitle.get(i));
            }
        }
    }
agile wigeon
#

assertEquals(new HashSet<>(list1), new HashSet<>(list2))

mint patio
#

what if you have 2 of the same in list1 and 3 of the same in list 2, arent they different?

hardy crag
agile wigeon
mint patio
#

exactly

#

but in arraylist

agile wigeon
mint patio
#

imagine this:

["orange", "apple", "orange", "orange"]
and
["apple", "orange", "orange"]

the hashset approach would tell you they are the same, though you have 3 orange in list1 and 2 times orange in list2

exotic barn
#

there wont be duplicate movie titles

mint patio
#

then why not using hashset in the first place?

hardy crag
# exotic barn ?

honestly simplest approach just sorting each and comparing them index by index, if you needed to do that with hashmap then you have to iterate through the arraylist and put each movie in a hashmap where the key is the movie and the value is integer of the count of it so far, then just iterate through the other one and get it from the hashmap, if there isn't then it wasn't in the first list and they aren't the same, if there's then just reduce the count and if the count was lower than 0 then remove that key completely from hashmap. you should end up with empty hashmap, if not then they aren't the same.

exotic barn
mint patio
#

best solution if you dont care about duplicates

exotic barn
#

sorry had to leave for an exam, but i tried using it

#
HashSet<ArrayList<Movie>> expectedSet = new HashSet<>();
        HashSet<ArrayList<Movie>> actualSet = new HashSet<>();
        expectedSet.add(Reader);
        actualSet.add(Array);
        assertEquals(expectedSet, actualSet);
#

java.lang.AssertionError:
Expected :[[ratings.Movie@2cfb4a64, ratings.Movie@5474c6c]]
Actual :[[ratings.Movie@4b6995df, ratings.Movie@2fc14f68]]

hardy crag
exotic barn
exotic barn
#

i tried running it and got

hardy crag
exotic barn
#

no

#

should i also show my method

hardy crag
# exotic barn no

you'll have to override the hashCode and equals since that's how hashmap differentiate between object from another, but if you don't want to do that then you can simply use TreeSet and pass a Comparator<Movie>

exotic barn
#

is there a different way

#

my TA said there was a simple way to do it with hashmaps, having the movie title as the key and movie cast as a value, and utilizing .contains

hardy crag
exotic barn
#

um

hardy crag
#

to your knowledge, hashset is just a hashmap in its core.

exotic barn
hardy crag
#

does the Movie class contain title and cast members? how do you know if movie1 is the same as movie2, do you compare their cast members and titles if they were equivalent or not?

exotic barn
#

movie class has String movietitle and an arraylist string of castmembers. im comparing the movietitle in my csv file with the movietitle from the expected i made

hardy crag
exotic barn
#

well i also do need to compare the cast, but i need to compare the title first since the cast is associated with the title

hardy crag
exotic barn
#

no duplicate casts

#

this is my csv file
Toy Story,Tom Hanks,Tim Allen
Jumanji,Robin Williams,Jonathan Hyde

acoustic crater
#

What exactly do you need to compare then

#

While reading from the csv file you can get the details of a movie at the same time

agile wigeon
hardy crag
hardy crag
# hardy crag you'll have to override the hashCode and equals since that's how hashmap differe...

@exotic barn just do the TreeSet way I mentioned, it's the easiest honestly. if you want to follow the TA's way then you'd have to

make hashmap of key string and value as anything that can hold cast members (List<String>, Map<String, Object>, etc)

iterate through first list and in each iteration put in the hashmap put in the hashmap key as the movie's title, and value as the cast members.

you either start decrement the previous hashmap by iterating the second movie list and removing from hashmap and you should end up with empty hashmap, or create another hashmap and repeat the process in the first one and assert if they're equals.

hardy crag
agile wigeon
#

๐Ÿค”