ArrayList removing items as string [duplicate] - java

This question already has answers here:
How do I remove objects from an array in Java?
(20 answers)
Closed 9 years ago.
I currently have an Arraylist as shown below.
T[] v = { v1,v2, v3, v4 };
I also have another array list:
removeT[] x = {v2, v4}
From the second, I would like these two values to be removed from the initial Array list. What are the required steps?

The best way to do it is something like this:
for (String each : removeT) {
if(v.equals(each)){
v.remove(each)
}
}
You can find more information on ArrayLists here.

I don't know of any operation that will do this directly on an array, so the solution I have to convert the arrays to a list:
String[] v = new String[]{ "v1", "v2", "v3", "v4" };
String[] x = new String[]{ "v1", "v4" };
List<String> list1 = new ArrayList<String>();
list1.addAll(Arrays.asList(v));
List<String> list2 = Arrays.asList(x);
list1.removeAll(list2);
and then when you are finished convert the list back to an array.
The problem of doing this directly on an array is that you would end up with null entries, which may create other issues, depending on your usage.

Related

How to get an array list and copy elements to a new list? [duplicate]

This question already has answers here:
Java ArrayList copy
(10 answers)
Closed 5 years ago.
Here is what I have to do:
Instantiates a new list array and copies the elements of the existing list array to the new list array. The list array instance variable becomes a pointer to the new list array.
I am working with array lists and methods. I have an array list with some numbers. I took numbers from that list but I don't know how to put the numbers that I took into a new array list.
HI Please check the below code.
ArrayList<Integer> oldlist = new ArrayList<>();
oldlist.add(0);
oldlist.add(1);
oldlist.add(2);
oldlist.add(3);
ArrayList<Integer> newList = new ArrayList<>();
newList.addAll(oldlist);
This is a basic problem in programming. It is usually called "iterating" or more specifically here: "iterating through / over a collection".
A classic way in Java would be:
ArrayList<Stuff> list2 = new ArrayList<>();
for (Stuff thing : list1) list2.add(thing);
You can read the second line as: "For each thing, of class Stuff, in list1, do..." The thing you want to do, is calling addon the second list.
As of Java7 you could do:
list1.forEach((thing) -> list2.add(thing));
Or even simpler:
ArrayList<Integer> newList = new ArrayList<>(oldList);

How to compare two lists of type string in java [duplicate]

This question already has answers here:
Java Compare Two Lists
(11 answers)
Closed 7 years ago.
I need to check whether elements of one list or array exists in other list.
The size of lists are same.
Apart from sorting is any simple solution possible?
You are right in saying that if they are arrays you can't use Arrays.equals(), if they are List<>s then you cannot just use equals. In both cases they also check order.
So yes your main option without writing your own comparison algorithm is to use Collections.sort() on both lists.
If you don't need to check for duplicates you could drop both lists into a HashSet using addAll and then compare the two HashSet or just use List.containsAll. The bad news though is that these would both have the same limitation, if you need to compare lists that might have repeated elements then it may give incorrect results. i.e. "bob", "bob", "fred" would compare as equal to "bob", "fred", "fred".
Please refer to the example below:
public class Example{
public static void main(String[] args){
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list1.add("A");
list1.add("B");
list1.add("C");
list2.add("C");
list2.add("X");
list2.add("Y");
for(String s : list1){
if(list2.contains(s)){
System.out.println("List 2 contains: " + s);
}
}
}
}
The code above is by all means not the cleanest or the most compact way to achieve what you are asking. But given the information presented, this should suffice.
To check if your an item of list1 is in list2 you could use this code:
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
//Adding some object to the list here
int yourIndex = 1;
if(list2.contains(list1.get(yourIndex)))
{
//do what you want
}

Remove duplicate elements from Array [duplicate]

This question already has answers here:
Java Remove Duplicates from an Array?
(10 answers)
Closed 8 years ago.
How to remove duplicate elements from array in java?
As we use Api remove() in ArrayList and converting ArrayList to hashset so in the same way how we will remove duplicate elements in Array?
Ideally you should write these small codes yourself. But if you are inclined on using apis,
Convert the arrays into a list and then put that in a Set.
List<Card> cardsList = Arrays.asList(arr);
String[] array = new HashSet<>(Arrays.asList(new String[] { "a", "b", "c", "b", "a" })).toArray(new String[0]);
System.out.println(Arrays.toString(array));
OUTPUT:
[b, c, a]
Convert Array to Set
String someArray[] = {"a","b","c","b"};
Set<String> mySet = new HashSet<String>(Arrays.asList(someArray));
for (String string : mySet) {
System.out.println(string);
}
So that all the duplicate elements will be removed because Set don't support it.
Ouput : b c a

Using the features in Java 8, what is the most concise way of transforming all the values of a list? [duplicate]

This question already has answers here:
Can a lambda be used to change a List's values in-place ( without creating a new list)?
(3 answers)
Closed 9 years ago.
Using the new features of Java 8, what is the most concise way of transforming all the values of a List<String>?
Given this:
List<String> words = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");
I am currently doing this:
for (int n = 0; n < words.size(); n++) {
words.set(n, words.get(n).toUpperCase());
}
How can the new Lambdas, Collections and Streams API in Java 8 help:
transform the values in-place (without creating a new list)
transform the values into a new result list.
This is what I came up with:
Given the list:
List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");
(1) Transforming them in place
Maybe I am missing it, there does not seem to be a 'apply' or 'compute' method that takes a lambda for List. So, this is the same as with old Java. I can not think of a more concise or efficient way with Java 8.
for (int n = 0; n < keywords.size(); n++) {
keywords.set(n, keywords.get(n).toUpperCase());
}
Although there is this way which is no better than the for(..) loop:
IntStream.range(0,keywords.size())
.forEach( i -> keywords.set(i, keywords.get(i).toUpperCase()));
(2) Transform and create new list
List<String> changed = keywords.stream()
.map( it -> it.toUpperCase() ).collect(Collectors.toList());
Maybe using the new stream concept in collections:
List<String> keywords = Arrays.asList("Apple", "Ananas", "Mango", "Banana", "Beer");
//(1)
keywords = keywords.stream().map(s -> s.toUpperCase()).collect(Collectors.toList());
//(2)
List<String> uppercaseKeywords = keywords.stream().map(s -> s.toUpperCase()).collect(Collectors.toList());

Get number of distinct elements in a sorted array [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Java - Distinct List of Objects
i have a sorted array of huge size (around 3000 strings) ,
i need to create an object for each distinct string ,
therefore i need create an array of objects with the size equal to distinct strings in the original array.
any suggestions?
Thanks
Well, if you need the distinct elements and not just the number, you may use a Set.
A Set is:
A collection that contains no duplicate elements.
You keep adding your elements to the set, and then just look at what the set contains.
Something similar to this:
public static String[] getDistinct(String[] input) {
Set<String> distinct = new HashSet<String>();
for(String element : input) {
distinct.add(element);
}
return distinct.toArray(new String[0]);
}
Usage:
String[] input = new String[] {"a", "b", "a", "c", "a", "b", "d"};
String[] distinct = getDistinct(input);
for(String element : distinct) {
System.out.println(element);
}
Result:
d b c a
Note that the order of the elements may not be preserved.
To find the number of the distinct elements, use:
getDistinct(input).length
pseudo code:
previous = Null
sum_size = 0
for (String current: yourarray) {
if (!current.equals(previous)) {
sum_size += current.size()
}
previous = current
}
sum_size is the added size of distinct elements in your array.
I think a Set is what you're looking for.

Categories

Resources