how to remove duplicate Element from Arraylist in java - java

{ "744101", "744101","744101", "744102",744102","744102","744102","744102","744103","744103"}
List<String> list2=new new ArrayList<String>(); //
Arrays.sort(iArr);
for(int k=0;k<iArr.length;k++) {
list2.add(String.valueOf(iArr[k]));
}
List li2 = new Array List(new HashSet(list2));
I'm unable to get result while trying to Sort Array list. Please correct me.

The TreeSet both sorts the elements and removes the duplicates.
String[] array = { "744101", "744101","744101", "744102","744102","744102","744102","744102","744103","744103"};
List<String> list = new ArrayList<>(new TreeSet<>(Arrays.asList(array)));
list.forEach((element)->{
System.out.println(element);
});

Try this:
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>();
hash.addAll(list);
list.clear();
list.addAll(hash);
And than sort list if you want.

As Eran mentioned, you current implementation "shuffles" the list due to HashSet implementation being used, as this Set implementation doesn't retain the order. Try using LinkedHashSet instead. As mentioned in javadoc it avoids overheads related to TreeSet.
Code would be something like this
String[] arrayToProcess = { "744101", "744101","744101", "744102","744102","744102","744102","744102","744103","744103"};
//creates array and sorts the list
List<String> sortedList = Arrays.asList(arrayToProcess);
Collections.sort(sortedList);
//removes duplicates the list, while retaining order of sorted list
Set<String> uniqueNumbers = new LinkedHashSet<String>();
uniqueNumbers.addAll(sortedList);
Note the implementation of Set being used is LinkedHashSet. Also this snippet makes two copies of the array so if array size is huge, I wouldn't suggest using it.
I would suggest you look up the implementations of collections in java. Because each of them has their own strengths and weaknesses:

Related

Java: How to efficiently remove strings from array that do not exist in the second array?

I have two big arrays of strings. I want to remove the elements from the first array that do not exist in the second array.
First I create two arrays:
Array to modify:
String[] sarr = fdata.split(System.getProperty("line.separator"));
ArrayList<String> items = new ArrayList(Arrays.asList(sarr));
Filter array:
List<String> filter = new ArrayList<String>();
filter = Arrays.asList(voc.split(System.getProperty("line.separator")))
Then I create Iterator to iterate through the elements of the items array and check if the iterated item exists in filter array, if it does, remove it from items:
Iterator<String> it = items.iterator();
while (it.hasNext()) {
String s = it.next();
if (!filter.contains(s)) {
it.remove();
}
}
items arrays contains 286,568 strings and filter contains 100,000 strings. It appears that the operation takes too much time so I am not doing it efficiently.
Is there a faster way?
Just use different collection types. For the Filter, use HashSet for O(1) (instad of O(n) for ArrayList) search complexity, and for the items, use LinkedList instead of ArrayList - which will be more efficient for the remove operations.
I didn't test this code, but...
String[] sarr = fdata.split(System.getProperty("line.separator"));
LinkedList<String> items = new LinkedList(Arrays.asList(sarr));
Set<String> filter = new HashSet<String>();
filter = new HashSet(Arrays.asList(voc.split(System.getProperty("line.separator"))));
items.retainAll(filter);
When you call collection.contains(element) often for a large collection, you should not use an ArrayList, but rather a HashSet.
Set<String> filter = new HashSet<>();
Collections.addAll(filter, voc.split(System.getProperty("line.separator")));
A HashSet is an optimized data structure for looking up things.

What does List<Set<Integer>> mean?

One of the questions I have been given asks:
All the lines should be stored in an object of
type List<Set<Integer>>.
How do you write this in Java, as in how do you initialise this list? I've never seen this before.
Please provide a link to an explanation as i'm not sure what this is called in Java so have no idea about how to learn about it. Thank You.
Its a List of Sets where each Set can hold only Integers.
Set<Integer> singlesSet = new HashSet<>();
singlesSet.add(1);
singlesSet.add(2);
Set<Integer> tensSet = new HashSet<>();
tensSet.add(10);
tensSet.add(20);
List<Set<Integer>> list = new ArrayList<>();
list.add(singlesSet);
list.add(tensSet);
System.out.println(list);
Example of usages of Set and List. Note that elements in a TreeSet are always sorted.
List<Set<Integer>> listofsets = new ArrayList<Set<Integer>>();
Set<Integer> set1 = new TreeSet<Integer>();
set1.add(1);
set1.add(2);
Set<Integer> set2 = new TreeSet<Integer>();
set2.add(6);
set2.add(4);
listofsets.add(set);
// listofsets = {{1,2}, {4,6}}
Like this List<Set<Integer>> yourList = new ArrayList<Set<Integer>>();?
You may want to take a look at https://docs.oracle.com/javase/7/docs/api/java/util/List.html
The short way:
List<Set<Integer>> list = new ArrayList<Set<Integer>>();
Set<Integer> set = new HashSet<Integer>();
list.add(set);
set.add(1);
set.add(2);
....
What is the difference between Set and List?
In Java, the List interface represents an abstract list of things. Any class the implements List (for example, LinkedList) must implement its methods and behave according to its contract.
You can essentially think of it as an array, but keep in mind that arrays are only one kind of list, and that implementations of List do no have to use arrays internally.
The Set also represents a collection of elements, but with no relationship or connection between them. Visually, you can think of a set as a sort of bag of things. You can add and remove things from the bag, but none of the items need to be related.
An Integer, of course, is just an object wrapper around Java's int primitive.
As such, a List<Set<Integer>> object would be similar to a two-dimensional array, only without a defined order in the second dimension.
You would initialize a List<Set<Integer>> as follows:
List<Set<Integer>> myList = new ArrayList<HashSet<Integer>>();
Where ArrayList and HashSet can be any classes that implement List and Set, respectively.

Java add variable to string array

I have a small code that includes citynames which will be displayed.
Now a want a user can add names with a scanner, I know the code for the scanner but not how to add the variable.
Code I have:
String[] cityNames = { "Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" };
System.out.println(Arrays.toString(cityNames));
No you cannot do it with a Array since the size is fixed , once it declared.
You are probably looking for Collections. Prefer to Use List interface with ArrayList implementation.
The reason is that the ArrayList is
Resizable-array implementation of the List interface.
List<String> cityNames = new ArrayList<>();
Now you have methods like add, remove, ... and many more useful methods on your cityNames List
You can use a List<String>, get the input value and add it:
List<String> cities = new ArrayList<>();
cities.add(userInput);
List is better to use than array as its length is modifiable.
Arrays have a fixed length. If the amount of Strings in your collection is variable, you´ll have to use a List.
You can add new element to array if index of new element less than the size of array.
arr[i]="some value" // to do this i < arr.length
If array is completely filled with elements when you assign new value to index previous value will override. You can't add more elements than the size of declared since array has fixed size.
Array is fixed size so you can't add the value to it if the size is already filled. For dynamic array use List instead of array.
Do like this
List<String> list = new ArrayList<String>(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren" ));
list.add("new value1");
list.add("new value2");
It's better to use there set, which excludes duplicate entries automatically:
Set<String> cities = new HashSet<String>();
cities.addAll(Arrays.asList("Tiel", "Culemborg", "Houten", "Geldermalsen", "Meteren", "Buren"));
then to add new city just call:
sities.add(newCity);
Scanner input = new Scanner(System.in);
List<String> cityNames = new ArrayList<String>();
//Add the city names to cityNames list...
cityNames.add(input.next());

in java,how to iterate list of objects

i am having the list myEmpls
List myEmpls = new ArrayList();
In this list i have added used defined objects.
LogConf e = getLogs(el);
//add it to list
myEmpls.add(e);
Now how to iterate the list of objects and get the values from this objects.
How to do this?
You could just google this and you would find tons of solutions.. But here is the code:
for(LogConf element : myEmpls) {
System.out.println(element.getValue());
}
You should also get used to define the type of the elements in the list:
List<LogConf> myEmpls = new ArrayList<LogConf>();
I know its been some time since this post was made. You can also use the Iterator.
List myEmpls = new ArrayList();
Iterator itr = myEmpls.iterator();
while(itr.hasNext()) {
LogConf Logobj = (LogConf) itr.next();
System.out.println(Logobj.getterName());
}
Hope this helps someone.

How get List from Set and Comparator

What is the "good" (and why ?) solution to get a List from a Set and sorted against a given Comparator ?
Set<Object> set = new HashSet<Object>();
// add stuff
List<Object> list = new ArrayList<Object>(set);
Collections.sort(list, new MyComparator());
Just construct it. The ArrayList has a constructor taking another Collection.
Set<Foo> set = new TreeSet<Foo>(new FooComparator<Foo>());
// Fill it.
List<Foo> list = new ArrayList<Foo>(set);
// Here's your list with items in the same order as the original set.
Either:
Set<X> sortedSet = new TreeSet<X>(comparator); ...
List<X> list = new ArrayList<X>(sortedSet);
or:
Set<X> unsortedSet = new HashSet<X>(); ...
List<X> list = new ArrayList<X>(unsortedSet);
Collections.sort(list, comparator);
Assuming that you start with an unsorted set or a set sorted on a different order, the following is probably the most efficient assuming that you require a modifiable List.
Set<T> unsortedSet = ...
List<T> list = new ArrayList<T>(unsortedSet);
Collections.sort(list, comparator);
If an unmodifiable List is acceptable, then the following is a bit faster:
Set<T> unsortedSet = ...
T[] array = new T[unsortedSet.size()];
unsortedSet.toArray(array);
Arrays.sort(array, comparator);
List<T> list = Arrays.asList(array);
In the first version, Collections.sort(...) copies the list contents to an array, sorts the array, and copies the sorted elements back to the list. The second version is faster because it doesn't need to copy the sorted elements.
But to be honest the performance difference is probably not significant. Indeed, as the input set sizes get larger, the performance will be dominated by the O(NlogN) time to do the sorting. The copying steps are O(N) and will reduce in importance as N grows.
This is how you get a List when you have a Set:
List list = new ArrayList(set);
Not sure what you expect to do with the Comparator. If the Set is sorted, the list will contain the elements in sorted order.

Categories