Deleting elements from list using another list - java

I am trying to delete the elements from list1 that are in list1
package listCollection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Arry2List {
public static void main(String[] args) {
String[] s = {"INDIA" ,"JAPAN","THAILAND","MALAYSIA"};
ArrayList<String> list1= new ArrayList<String>();
String[] s1 = {"THAILAND","MALAYSIA"};
ArrayList<String> list2= new ArrayList<String>();
for(String temp : s)
{
list1.add(temp);
}
for(String temp : s1)
{
list2.add(temp);
}
//removing elements from list1 that are in list2
System.out.println("In list1 **************");
for (String t : list1)
{
System.out.println(t);
}
System.out.println("In list2 **************");
for (String t1 : list2)
{
System.out.println(t1);
}
//editlist(list1,list2);
Iterator<String> i=list1.iterator();
while( i.hasNext() )
{
if ( list2.contains( i.hasNext() ) )
{
i.remove();
}
}
System.out.println("In list1 again **************");
for(int i1 =0;i1<list1.size();i1++)
{
System.out.println(list1.get(i1));
}
}
}
Output should be INDIA,JAPAN.
List1 should contain only those elements which are not in the list2.
I am a beginner to Core Java and trying to learn collections.

In the loop that checks the element using List.contains(), you're passing a boolean (i.hasNext() returns whether the iterator has more elements) instead of the element. This causes the loop to run infinitely because you never call Iterator.next() to get the next element. You should use:
if (list2.contains(i.next())) {
instead of
if (list2.contains(i.hasNext())) {
It's better practice to also save the next element in a variable for re-usability:
while (i.hasNext()) {
String element = i.next();
if (list2.contains(element)) {
i.remove();
}
}

There is a built-in method to do that:
list1.removeAll(list2)
[EDIT]
You can create the lists easier using Arrays.asList:
List<String> list1 = new ArrayList<String>(Arrays.asList("INDIA", "JAPAN", "THAILAND", "MALAYSIA"));
List<String> list2 = Arrays.asList("THAILAND", "MALAYSIA");
list1.removeAll(list2);
[EDIT2]
The Arrays.asList produces unmodifiable list, so we have to use it to initialize a modifiable one.
[EDIT3]
Your code doesn't work because you don't advance the iterator. i.hasNext() only checks if there is a next element. It returns true or false, not the element itself. Here is how to fix this:
while (i.hasNext()) {
if (list2.contains(i.next())) {
i.remove();
}
}
You can also iterate over the list2 elements and remove them from list1:
for (String el : list2) {
list1.remove(el);
}

Related

String inside ArrayList<String[]>

How to check whether a specific String is present inside ArrayList<String[]>?
Whether I need to iterate each item and check for the string or any specific method for this purpose is present (like ArrayList.contains() )?
Tried ArrayList.contains() but not working in my case.
It is not an ArrayList <String> it is ArrayList<String[]> so this question is not a duplicate one and am asking this for a curiosity whether any special method is present or not
This is a example program to get what you asked for... hope it helps
public static void main(String[] args) {
ArrayList<String []> a = new ArrayList<>();
String b[] = {"not here","not here2"};
String c[] = {"not here3","i'm here"};
a.add(b);
a.add(c);
for (String[] array : a) {// This loop is used to iterate through the arraylist
for (String element : array) {//This loop is used to iterate through the array inside the arraylist
if(element.equalsIgnoreCase("i'm here")){
System.out.println("found");
return;
}
}
}
System.out.println("match not found");
}
You can do it easily with streams:
String contains;
List<String[]> strings;
boolean isPresent = strings.stream().flatMap(Arrays::stream).anyMatch(contains::equals);
Well, you need to traverse whole list and then traverse each array inside it to find the item.
String valToBeSearched="abc";
for(String [] arr: list)
{
for(String str: arr)
{
if(str.equals(valToBeSearched)){ // do your stuff}
}
}
Using Java 8 streams, you can do this:
public boolean containsString(List<String[]> list, String s) {
// Gives you a Stream<String[]>.
return list.stream()
// Maps each String[] to Stream<String> (giving you a
// Stream<Stream<String>>), and then flattens it to Stream<String>.
.flatMap(Arrays::stream)
// Checks if any element is equal to the input.
.anyMatch(Predicate.isEqual(s));
}
You could iterate over the ArrayList with two for-each loops:
import java.util.Arrays;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String[]> arrayList = new ArrayList<String[]>();
String[] fruit = {"Apple", "Banana"};
String[] pets = {"Cat", "Dog"};
arrayList.add(fruit);
arrayList.add(pets);
System.out.println(Arrays.deepToString(arrayList.toArray())); //[[Apple, Banana], [Cat, Dog]]
System.out.println(arrayListContains(arrayList, "Apple")); //true
System.out.println(arrayListContains(arrayList, "Orange")); //false
}
public static boolean arrayListContains(ArrayList<String[]> arrayList, String str) {
for (String[] array : arrayList) {
for (String s : array) {
if(str.equals(s)) {
return true;
}
}
}
return false;
}
}
Try it here!
Try to take a look at Guava Iterables.concat().
It can be used to flatten Iterable of Iterables, i'm not sure it will work on an Iterable of Array but it's just a little transformation...
If you can flatten your list, you could then use the "contains" method on the result.

ArrayList with two methods in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have an arraylist in java and 2 methods for it. I want to use these two methods for my arraylist at once.
In the first method, I have used the method remove(), so the arraylist doesn't have all of its elements anymore.
For the second method, I also need to have the arraylist with all of its elements. But the Arraylist is not the same anymore.
I am thinking about multithreading in java. Is there another way to solve this problem?
Here is my code:
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<String> list = new ArrayList<String>();
// Adding items to arrayList
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
System.out.println("The arraylist contains the following elements: " + list);
method1(list);
method2(list);
}
public static void method1(List<String> list) {
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String s = iterator.next();
if (!s.startsWith("a")) {
iterator.remove();
}
}
System.out.println("List1: " + list);
}
public static void method2(List<String> changedFilesList) {
for (Iterator<String> iterator = changedFilesList.iterator(); iterator.hasNext();) {
String s = iterator.next();
if (!s.startsWith("b")) {
iterator.remove();
}
}
System.out.println("List2:" + changedFilesList);
Output:
The arraylist contains the following elements: [aaa, bbb, ccc, ddd]
List of the other: [aaa]
List of the other: []
Expected Output:
The arraylist contains the following elements: [aaa, bbb, ccc, ddd]
List of the other: [aaa]
List of the other: [bbb]
Those two methods look too much alike, you should combine them in to one. Also, how about looking at it a different way? In stead of removing stuff from the list, add them to another.
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");
System.out.println("The arraylist contains the following elements: " + list);
System.out.printLn("List 1: " + method(list, "a"));
System.out.printLn("List 2: " + method(list, "b"));
}
private List<String> method(List<String> list, String filter) {
List<String> filteredList = new ArrayList<>();
for (String s : list) {
if (s.startsWith(filter)) {
filteredList.add(s);
}
}
return filteredList;
}
Make a copy of the list before calling the first method:
List<String> list2 = new ArrayList(list);
Then, call method1 with list and method2 with list2.
As ArrayList implements Cloneable you can use the following before calling method2():
final List<String> copy = (List) list.clone();
Call method2() as follows:
method2(copy);
Try this
public static void method1(List<String> list) {
List<String> list1=new ArrayList<String>();
list1.addAll(list);
for (Iterator<String> iterator=list1.iterator();iterator.hasNext();{
String s = iterator.next();
if (!s.startsWith("a")) {
iterator.remove();
}
}
System.out.println("List1: " + list1);
}
public static void method2(List<String> changedFilesList) {
List<String> list1=new ArrayList<String>();
list1.addAll(changedFilesList);
for (Iterator<String> iterator=list1.iterator();iterator.hasNext();{
String s = iterator.next();
if (!s.startsWith("b")) {
iterator.remove();
}
}
System.out.println("List2:" + list1);
}

Java ArrayList<String> .contains() in hadoop

I am trying to remove the duplicated strings in an ArrayList called outputList in Hadoop.
Here is my code:
List<String> newList = new ArrayList<String>();
for( String item : outputList){
if(!newList.contains(item))
newList.add(item);
else newList.add("wrong");
}
The problems is that the strings in newList are all "wrong".
Some facts:
1. The above code works well at local machine.
I can write out the strings in outputList in hadoop. Most strings in outputList are different (duplicates exist).
I tried some other method to remove duplicated items. Like using HashSet. But when I use outputList to initialize a HashSet, the obtained HashSet is empty.
The java version in Hadoop is javac 1.6.0_18
Thanks.
The following is my reducer code:
public static class EditReducer
extends Reducer<Text,Text,Text,Text> {
private Text editor2 = new Text();
public void reduce(Text key, Iterable<Text> values,
Context context
) throws IOException, InterruptedException {
//write the content of iterable to an array list.
List<String> editorList =new ArrayList<String>();
for (Text t:values) {
editorList.add(t.toString());
}
//if a user appears more than once in the list, add to outputList
int occ;
List<String> outputList =new ArrayList<String>();
for (int i=0;i<editorList.size();i++) {
occ= Collections.frequency(editorList, editorList.get(i));
if(occ>1) {
outputList.add(editorList.get(i));
}
}
//make outputList distinct
List<String> newList = new ArrayList<String>();
for( String item : outputList){
if(!newList.contains(item))
newList.add(item);
else newList.add("wrong");
}
for (String val : newList) {
editor2.set(val);
context.write(editor2,editor2);
}
}
}
You can create a nested for loop inside your original for loop and compare the strings that way:
List<String> newList = new ArrayList<String>();
for(String item : outputList) {
boolean contains = false;
for(String str: newList) {
if(str.equals(item)) {
contains = true;
break;
}
}
if(!contains) {
newList.add(item);
}
else {
newList.add("wrong");
}
}

how to remove blank items from ArrayList.Without removing index wise

public class ArrayListTest {
public static void main(String[] args) {
ArrayList al=new ArrayList();
al.add("");
al.add("name");
al.add("");
al.add("");
al.add(4, "asd");
System.out.println(al);
}
}
o/p [, name, , , asd]
desire O/p [name,asd]
You can use removeAll(Collection<?> c) :
Removes all of this collection's elements that are also contained in
the specified collection
al.removeAll(Arrays.asList(null,""));
This will remove all elements that are null or equals to "" in your List.
Output :
[name, asd]
You can remove an object by value.
while(al.remove(""));
Iterate over the list, read each value, compare it to an empty string "" and if it is that, remove it:
Iterator it = al.iterator();
while(it.hasNext()) {
//pick up the value
String value= (String)it.next();
//if it's empty string
if ("".equals(value)) {
//call remove on the iterator, it will indeed remove it
it.remove();
}
}
Another option is to call List's remove() method while there are empty strings in the list:
while(list.contains("")) {
list.remove("");
}
List<String> al=new ArrayList<String>();
...................
for(Iterator<String> it = al.iterator(); it.hasNext();) {
String elem = it.next();
if ("".equals(elem)) {
it.remove();
}
}
I do not comment this code. You should study from it yourself. Please pay attention on all details.

To get the Iterator running in Java

I have the following code sample, im pretty sure the first block should be placed in the main(), but where do I place the second block to make this Iterator example work?
List<String> myList= new ArrayList<String> ( );
Where do i place this? Would I need to create a second class?
static void printAll(ArrayList myList)
{
Iterator it = myList.iterator();
}
then there's this typical iterator pattern....is this in any way related to the second code block?
static void printAll(ArrayList myList)
{
Iterator it = myList.iterator();
Object temp;
while( it.hasNext() )
{
temp = it.next();
System.out.println( temp );
}
return;
}
It isn't clear what you want to achieve, if you are asking how to pass your ArrayList (local variable in main) to the printAll method, do something like below:
public class XYZ {
static void printAll(ArrayList myList)
{
Iterator it = myList.iterator();
Object temp;
while(it.hasNext() )
{
temp = it.next();
System.out.println( temp );
}
return;
}
public static void main(String...args){
List<String> myList= new ArrayList<String> ( );
myList.add("Hello");
myList.add("World");
printAll(myList);//passing myList to printAll
}
}
Is there a reason you're trying to use an interator?
You can do something like this, assuming you're on Java 5.
List<String> myList= new ArrayList<String> ( );
// set up list... etc.
for(String currentString : myList) {
System.out.println(currentString);
}
Iterators are only useful if you need to remove some element of the collection while traversing it (using the Iterator.remove() method). Otherwise, just use a for-each loop.

Categories

Resources