I'm trying to create a method that finds every unique word in a list and then adds them to a new list. I have tried the following:
public static void countWords(){
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
String inText = JOptionPane.showInputDialog(null, "Type in text");
int start = 0;
for(int i = 0; i < inText.length(); i++) {
if(inText.charAt(i) == ' ') {
list1.add(inText.substring(start,i));
start = i;
}
}
for(int a = 0; a < list1.size(); a++) {
for(int j = 0; j < a; j++) {
if(list1.get(a) != list2.get(j)) {
list2.add(list2.get(a));
}
}
}
}
When I run the program and type in "hi hi hi" I get this error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.get(ArrayList.java:429)
at RäknaOrd.countWords(RäknaOrd.java:24)
at RäknaOrd.main(RäknaOrd.java:6)
How could I fix this error? Would my approach even work?
Java 8 has a nice stream based method to return a new list with duplicates removed :
List<String> list2 = list1.stream().distinct().collect(Collectors.toList());
Also to split the String and get a List<String> you can avoid a for loop like this :
List<String> list1 = Arrays.asList(inText.split(" "));
But keep in mind that list1 is immutable in this case.
A minimal example for demonstration would be :
String inText = "hi hi hi";
List<String> list1 = Arrays.asList(inText.split(" "));
List<String> list2 = list1.stream().distinct().collect(Collectors.toList());
System.out.println(list2);
Which prints [hi]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With