Skip to content
Advertisement

Java, comparing a Linked List to an Array

Working on a Java program that will read in two different passages, convert both strings to arrays of strings for each word, and then String One to a linked list, which will promptly be sorted into alphabetical order.

After the list has been sorted, I get confused. I have a for loop written to get the length of array2 to advance it as needed, but what would be a good loop for advancing through a linked list? It may be basic, but nothing comes to mind.

EDIT: Left this bit of information out. My bad. The point is to compare the array and the linked list word by word, and if two words match up, that word and node will be removed from the linked list.

And also, another question regarding the Java LinkedList class, is there a delete function? And if so, does it automatically pull it back and link the two threads?

I have already tested to see if the strings are being assigned properly and they are.

The program is below.

package algorithm;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.List;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class main 
{

    public static void main (String[] args) throws FileNotFoundException
    {   
        String input1 = new Scanner(new File("passage1.txt")).useDelimiter("\Z").next();
        String input2 = new Scanner(new File("passage2.txt")).useDelimiter("\Z").next();
        String[] array1 = input1.split(" ");
        String[] array2 = input2.split(" ");

        List<String> list = new LinkedList(Arrays.asList(array1));

        Collections.sort(list);

        int length = array2.length;

        for (int c = 0; c < length; c++)
        {
            // LinkedList loop here


        }
    }
}

Advertisement

Answer

Simply you can use boolean removeAll(Collection<?> c) method which is defined in the List interface. What you have to do is, you need to make as instance of Collection. In your case,

List<String> list = new LinkedList(Arrays.asList(array1));
Collections.sort(list);
List<String> toRemove = new LinkedList(Arrays.asList(array2));
list.removeAll(toRemove);

Now the list object will contains the element that are not present in toRemove object.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement