Remove duplicate elements from Array [duplicate] - java

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

Related

Sort List<String[]> based on first element each [duplicate]

This question already has answers here:
Sort ArrayList of Array in Java
(7 answers)
Java how to sort a Linked List?
(9 answers)
Closed 1 year ago.
I have a linked list of arrays of strings.
List<String[]> list = new LinkedList<>();
Each element of this list contains elements of the form:
["word1", "example1", "2"]
How do I sort the list by the first string element in each array lexicographical?
You need to provide a Comparator that compares the first values of the arrays.
list.sort(Comparator.comparing(a -> a[0]));
Test
List<String[]> list = new LinkedList<>();
list.add(new String[] { "word1", "example1", "2" });
list.add(new String[] { "ahead", "invention", "3" });
list.add(new String[] { "sip", "nerve", "4" });
list.sort(Comparator.comparing(a -> a[0]));
list.forEach(a -> System.out.println(Arrays.toString(a)));
Output
[ahead, invention, 3]
[sip, nerve, 4]
[word1, example1, 2]
Can use the below code for sorting a List. I guess this should suffice your purpose.
Collections.sort(list, new Comparator<String[]>() {
#Override
public int compare(String[] arr1, String[] arr2) {
return arr1[0].compareTo(arr2[0]);
}
});
If you're using Java 8 and above, then you can achieve the same with below line of code.
list.sort((arr1, arr2) -> arr1[0].compareTo(arr2[0]));

convert array to List using ArrayList's constructor [duplicate]

This question already has answers here:
Why does Arrays.asList() return its own ArrayList implementation
(6 answers)
Closed 8 years ago.
The method Arrays.asList(<T>...A) returns a List representation of A.
The returned object here is a List backed by an array, but is not an ArrayList object.
I'm looking for the differences between the object Arrays.asList() returns and an ArrayList object-- a quick source to tell these without diving into the code.
TIA.
When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is a fixed size list backed by the original source array. In other words, it is a view for the array exposed with Java's collection-based APIs.
String[] sourceArr = {"A", "B", "C"};
List<String> list = Arrays.asList(sourceArr);
System.out.println(list); // [A, B, C]
sourceArr[2] = ""; // changing source array changes the exposed view List
System.out.println(list); //[A, B, ]
list.set(0, "Z"); // Setting an element within the size of the source array
System.out.println(Arrays.toString(sourceArr)); //[Z, B, ]
list.set(3, "Z"); // java.lang.ArrayIndexOutOfBoundsException
System.out.println(Arrays.toString(sourceArr));
list.add("X"); //java.lang.UnsupportedOperationException
list.remove("Z"); //java.lang.UnsupportedOperationException
You cannot add elements to it and you cannot remove elements from it. If you try to add or remove elements from them you will get UnsupportedOperationException.
I'll expand my comment a little bit.
One problem that can occur if you use asList as it wasn't different from ArrayList object:
List<Object> list = Array.asList(array) ;
list.remove(0); // UnsupportedOperationException :(
Here you cannot remove the 0 element because asList returns a fixed-size list backed by the specified array. So you should do something like:
List<Object> newList = new ArrayList<>(Arrays.asList(array));
in order to make the newList modifiable.

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
}

ArrayList removing items as string [duplicate]

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.

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