1
    { "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.

2
  • It's not clear if you want just to remove duplicates, or to both remove duplicates and sort the output. Your current code sorts the input array, but adding the elements to the HashSet destroys the order (while eliminating the duplicates). Commented Jan 16, 2016 at 10:16
  • my current code is Sorted but duplicate element coming i dont want duplicate Commented Jan 16, 2016 at 10:20

3 Answers 3

2

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);
    });
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.