Thanks for the help from Zirak In my previous post i implemented the following in JavaScript:
var arr1 =[0,1,2,3];
var arr2 =["ac", "bc", "ad", "e"];
var result = arr1 .sort(function(i, j){return arr2[i].localeCompare(arr2[j])})
document.write(result );
The way to achieve this is quite compact in JavaScript, can a java implementation of this be also achieved by such simplicity? I could only think of implementing the Comparable interface like the following:
public class testCompare {
public static String[] arr2={"ac", "bc", "ad", "e"};
public static Obj[] arr1={new Obj(0), new Obj(1), new Obj(2), new Obj(3)};
static class Obj implements Comparable{
int index=0;
public Obj(int i){
index=i;
}
#Override
public int compareTo(Object o) {
return arr2[index].compareTo(arr2[((Obj)o).index]);
}
}
}
but if the array have X many items, then I will have to create X many Objs, is there another way that I could achieve this more simply? Another question is, if I do the above method what would be the time complexity for the sorting both in java and in JavaScript, are they all O(n^2)? Thanks a lot
public class MyComparator implements Comparator<Integer> {
#Override
public int compare(Integer i1, Integer i2) {
return arr2[i1.intValue()].compareTo(arr2[i2.intValue()]);
}
}
Arrays.sort(arr1, new MyComparator());
This is the equivalent of the JavaScript sort. The Comparator object is used as the callback function is used in JavaScript.
Try using a TreeMap<String, Integer> (assuming you want to sort integers) which means all entries are sorted by their string key:
SortedMap<String, Integer> map = new TreeMap<String, Integer>();
map.put("ac", 0);
map.put("bc", 1);
map.put("ad", 2);
map.put("e", 3);
for( Map.Entry<String, Integer> entry : map.entrySet() )
{
System.out.println(entry.getKey() + " - " + entry.getValue());
}
Output:
ac - 0
ad - 2
bc - 1
e - 3
To sort an array and get the new order of the previous indices you could iterate over the array and add the indices as Integer objects to the map:
String[] input = {"ab", "bc", "ad" , "e" };
SortedMap<String, Integer> map = new TreeMap<String, Integer>();
for( int i = 0; i < input.length; ++i )
{
map.put(input[i], i); //or use values from another array, e.g. map.put(inputKeys[i], inputValues[i]);
}
If you need to sort the keys by anything else but the natural order, you can add a Comparator<String> to the TreeMap constructor.
public class SortA1byA2array
{
public static void main (String[] args)
{
int[] arr1={2,1,2,5,7,1,9,8,3,6,8,8};
int[] arr2={2,1,8,3};
TreeMap hm=new TreeMap();
int count=1;
for(int i=0;i<arr1.length;i++){
if(hm.containsKey(arr1[i])){
hm.put(arr1[i], ++count);
}
else{
count=1;
hm.put(arr1[i],count);
}
}
for(int i=0;i<arr2.length;i++){
if(hm.containsKey(arr2[i])){
for(int j=0;j<(Integer)hm.get(arr2[i]);j++){
System.out.println(arr2[i]);
}
hm.remove(arr2[i]);
}
}
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey());
it.remove();
}
}
}
In response to the second part of you question: Arrays.sort in Java has guaranteed O(n log n) time complexity, as specified in the API.
Related
I am trying to split each element of an ArrayList into a char and double and push the results into a HashMap. So far, my code is this:
public static int TotalAmount(ArrayList<String> x) {
HashMap<Character,Double> hm = new HashMap<Character,Double>();
for(int i = 0; i < x.size(); i++) {
String[] s = x.get(i).split("(?<=\\d)(?=[a-zA-Z])");
hm.put(s[1].charAt(0), Double.parseDouble(s[0]));;
}
I do this with the ArrayList holding:
234K
1.3M
2.1M
211H
11K
But when I iterate through the HashMap, I get:
H, 211
K, 11
M, 2.1
I cannot seem to find where my logic went wrong. I might be able to accredit this to my intro to HashMaps. How do I ensure that I convert the ArrayList of Strings into a HashMap correctly?
To clear things up, I'm trying to completely move the ArrayList into a HashMap, without overwriting when the same key is found.
You can try this:
public static HashMap<Character, List<Double>> TotalAmount(ArrayList<String> initialList) {
HashMap<Character, List<Double>> resultMap = new HashMap<>();
for (String line : initialList) {
Double size = Double.parseDouble(line.substring(0, line.length() - 1));
Character sizeChar = line.charAt(line.length() - 1);
if (resultMap.containsKey(sizeChar)) {
resultMap.get(sizeChar).add(size);
} else {
resultMap.put(sizeChar, Collections.singletonList(size));
}
}
return resultMap;
}
Try this! I tested and it works fine! As QBrute mentioned, HashMap's put() overrides any value that is processed with the same key earlier.
I created method and the test(in main) using HashMap>
.
import java.util.*;
public class Question {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("234K");
list.add("1.3M");
list.add("2.1M");
list.add("221H");
list.add("11K");
HashMap<Character, ArrayList<Double>> result = TotalAmount(list);
System.out.println("K: " + result.get('K'));
System.out.println("M: " + result.get('M'));
System.out.println("H: " + result.get('H'));
}
public static HashMap<Character, ArrayList<Double>> TotalAmount(
ArrayList<String> x) {
HashMap<Character, ArrayList<Double>> map = new HashMap<>();
for (String line : x) {
Double num = Double.parseDouble(line.substring(0,
line.length() - 1));
Character c = line.charAt(line.length() - 1);
if (map.containsKey(c)) {
map.get(c).add(num);
} else {
ArrayList<Double> newList = new ArrayList<>();
newList.add(num);
map.put(c, newList);
}
}
return map;
}
}
Supose a I have the following array:
String[ ] array = new String {
{ a2, a4, a5, a1, a3 },
{5.0, 2.0, 5.0, 2.0, 2.0 }
};
Arranged as a 5X2 matrix:
(a2; 2.0)
(a4; 2.0)
(a5; 2.0)
(a1; 5.0)
(a3; 5.0)
I wish to concatenate the rows of the first column using as criteria the values in second one, generating the following 2X2 matrix:
("a2, a4, a5"; 2.0)
("a1, a3"; 5.0)
Thanks!
First thing we need to do is change your array type to Object[][] so it can hold both strings and numbers:
Object[][] array = {
{ "a2", "a4", "a5", "a1", "a3" },
{ 5.0, 2.0, 5.0, 2.0, 2.0 }
};
Now we use streams to produce a map of concatenated string values grouped by their corresponding numeric value, then we stream the map entries into a 2-column matrix:
Object[][] grouped = IntStream.range(0, array[0].length) // this will create a stream containing as many natural numbers, starting from 0, that the array has elements
.boxed() // this will make it a stream of Integers instead of ints
.collect(groupingBy(i -> array[1][i], mapping(i -> array[0][i].toString(), joining(", ")))) // here, we make a Map out of the stream by grouping by the i'th element of the second column in the matrix and taking as the value the respective element from the first column, then joining the resulting list of strings in the map's value with a ", " separator
.entrySet() // now we take the entry set of the map
.stream() // we stream it
.map(e -> new Object[] {e.getValue(), e.getKey()}) // and we transform each entry in the map into a matrix row
.toArray(Object[][]::new); // finally, we transform the stream of rows into a matrix (array of rows)
The above relies on a static import of java.util.stream.Collectors.*.
This can easily be adapted to work with a pure string matrix, if that's what you're after.
Don't know how the numbers you have are stored, but assuming that they are BigDecimals (for hashing reasons), use Map<BigDecimal, StringBuilder> to aggregate items. So, if your map already contains() the given decimal, append() to the respective StringBuilder, if not, create a new one. Also, as for iterating over the matrix, use a for loop with a shared index to iterate over the two arrays in parallel.
I don't think this is the best/safest code (I'm making some assumptions on the array), but it will get you started.
First, fix your array:
String[][] array = new String[][]{{"a2","a4","a5","a1","a3"},
{"5.0", "2.0", "5.0", "2.0", "2.0"}};
Now,
Map<String, StringBuilder> map = new HashMap<>();
for (int i = 0; i < array[0].length; i ++) {
map.putIfAbsent(array[1][i], new StringBuilder());
map.get(array[1][i]).append(array[0][i]).append(" "); // Build the collected "a1, a3" grouping by the second value;
}
String[][] result = new String[2][map.size()];
int j = 0;
for(Map.Entry<String, StringBuilder> entry : map) {
result[j][0] = entry.getValue().toString();
result[j][1] = entry.getKey();
}
I think I can do this with streams, but I'll have to think about it.
This is how I would solve the problem without using streams. However, like other people said, I was unsure of which were the data types to use.
private static final int SIZE_KEY_PLUS_CONCATENATION = 2;
private static final int INDEX_OF_KEY = 1;
private static final int INDEX_OF_VALUE = 0;
private static final String SEPARATOR = ", ";
private static final int RESULT_KEY = 0;
private static final int RESULT_VALUE = 1;
private static final String RESULT_SEPARATOR = " : ";
public static void main(String[] args) {
String[][] matrix = new String[][]{
{"a2", "5.0"},
{"a4", "2.0"},
{"a5", "5.0"},
{"a1", "2.0"},
{"a3", "2.0"},
};
String[][] result = getConcatenatedMatrix(matrix);
for(String[] row : result) {
System.out.println(row[RESULT_KEY] + RESULT_SEPARATOR + row[RESULT_VALUE]);
}
}
private static String[][] getConcatenatedMatrix(String[][] inputMatrix) {
Map<String, String> map = generateMapWithConcatenatedValues(inputMatrix);
return convertMapToMatrix(map);
}
private static Map<String, String> generateMapWithConcatenatedValues(String[][] inputMatrix) {
Map<String, String> map = new HashMap<>();
for(String[] row : inputMatrix) {
String key = row[INDEX_OF_KEY];
String value = row[INDEX_OF_VALUE];
doConcatenation(key, value, map);
}
return map;
}
private static void doConcatenation(String key, String value, Map<String, String> map) {
if(map.containsKey(key)) {
map.put(key, map.get(key) + SEPARATOR + value);
} else {
map.put(key, value);
}
}
private static String[][] convertMapToMatrix(Map<String, String> mapToConvert) {
int keyCount = mapToConvert.size();
String[][] result = new String[keyCount][SIZE_KEY_PLUS_CONCATENATION];
Set<String> keys = mapToConvert.keySet();
int currentKey = 0;
for(String key : keys) {
result[currentKey][RESULT_KEY] = key;
result[currentKey][RESULT_VALUE] = mapToConvert.get(key);
currentKey++;
}
return result;
}
I have finally gotten my code to where it works. Although it isnt the easiest to read.
I am reading from a text file that has
Date/time Tip from xxx
tip totalAmount
My code now takes the amount tipped by a person and adds them together. eg X tip 10, X tip 20, X tip 30, Y tip 200, Z tip 30, Z tip 40 and outputs
X=60
Y=200
Z=70
I did this by turning my Map< String,Integer> into an Object[] tipsPerPerson
So how would I go about sorting this Object[] tipsPerPerson into something a bit easier to read (theres over 2000 names) a bit like this
Y=200
Z=70
X=60
Here is a portion of the code that im stuck at
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
public class Tip {
public static void main(String[] args)
{
int lineNumber = 1;
Map<String, Integer> tipsByName = new HashMap<String, Integer>();
String fileName = "C:\\Users\\David\\Desktop\\tips.txt";
System.out.println("Reading text from file");
try {
FileReader inputFile = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(inputFile);
String line;
String currentTipper = null;
while ((line = bufferedReader.readLine()) != null) {
if (lineNumber % 2 != 0) {
final String tipperName = line.substring(line.indexOf("from ") + 5);
currentTipper = tipperName;
} else {
final Integer tipValue = Integer.parseInt(line.substring(0, line.indexOf("\t")));
// here we store the tip in the map. If we have a record we sum, else
// we store as is
tipsByName.put(currentTipper, (tipsByName.get(currentTipper) == null ? 0 : tipsByName.get(currentTipper))
+ tipValue);
}
lineNumber++;
}
bufferedReader.close();
Object[] tipsName = tipsByName.entrySet().toArray();
for (int i = 0; i < tipsByName.size(); i++) {
System.out.println(tipsName[i]); // output the map
}
} catch (Exception e) {
System.out.println("Error while reading file line by line: " + e.getMessage());
}
}
}
Just dump the entries into a list and sort them using a Comparator:
List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b) {
return Integer.compare(b.getValue(), a.getValue());
}
});
Note that b is compared to a, rather than the other way around, to give us reverse order (largest to smallest).
All done in two lines. If you then iterate over the list, it will be in the order you wanted. Use getKey() and getValue() to print, or simply use the default toString() of the Entry:
for (Map.Entry<String, Integer> entry : entries)
System.out.println(entry + '\n');
An advice: use the map and d'ont make any array convertions.
The map class gives you all that you need.
You can iterate over the keys or over the values or over both like you do right now.
Just use the key values of your map and pass it as an argument to
Collections.sort(). This works because the returned key set is of type Collection
which can be passed to the Collections.sort() method.
Than it will be ordered in alphabetical order.
If you want something else just pass an additonal Comparator class to the Collection.sort()
or wrap your object within a customized class which implements the
interface Comparable.
After that you just iterate throught you keys and
invoke map.get(key) method.
Example:
Iterator<String> sortedKeys = map.keySet().iteator();
for (String key :keys) {
sysout(key: "+key+" value : "+ map.get(key));
}
Hope it was thge answer you needed.
Ouch. Don't do that! Try this instead...
// Get the Entries.
java.util.Set<Entry<String, Integer>> entrySet = tipsByName
.entrySet();
// Make a SortedSet with a Custom Comparator.
SortedSet<Entry<String, Integer>> sortedSet = new TreeSet<Entry<String, Integer>>(
new Comparator<Entry<String, Integer>>() {
public int compare(
Entry<String, Integer> o1,
Entry<String, Integer> o2) {
if (o1 == o2) {
return 0;
} else if (o1 == null) {
return -1;
} else if (o2 == null) {
return 1;
}
return o1.getValue().compareTo(
o2.getValue());
}
});
// Add the Entries to the SortedSet.
for (Entry<String, Integer> entry : entrySet) {
sortedSet.add(entry);
}
// Iterate the sortedSet.
Iterator<Entry<String, Integer>> iter = sortedSet
.iterator();
while (iter.hasNext()) {
System.out.println(iter.next()); // print your sorted items.
}
I'm trying to get results HashMap sorted by value.
This is HashMap's keys and values:
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
I try to get results like this:
1 = can
2 = selin
4 = burak
5 = ertu
Here is my code:
import java.util.*;
public class mapTers {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext()) {
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++) {
while (t.hasNext()) {
if (dizi[i].equals(map.get(t.next()))) {
System.out.println(dizi[i] + " = " + t.next());
}
}
}
}
}
You can sort the entries as follows (but note this won't sort the map itself, and also HashMap cannot be sorted) -
List<Map.Entry<String, Integer>> entryList = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
Every time that you call t.next(), the iterator's pointer is moved forward. Eventually, the iterator reaches the end. You need to reset the iterator. Also, calling t.next() twice moves the pointer twice.
Here's my solution:
import java.util.*;
public class mapTers
{
public static void main(String[] args)
{
HashMap<String, Integer> map = new HashMap<String, Integer>();
map.put("ertu", 5);
map.put("burak", 4);
map.put("selin", 2);
map.put("can", 1);
Integer dizi[] = new Integer[map.size()];
Set anahtarlar = map.keySet();
Iterator t = anahtarlar.iterator();
int a = 0;
while (t.hasNext())
{
dizi[a] = map.get(t.next());
a++;
}
Arrays.sort(dizi);
for (int i = 0; i < map.size(); i++)
{
t = anahtarlar.iterator();
while (t.hasNext())
{
String temp = (String)t.next();
if (dizi[i].equals(map.get(temp)))
{
System.out.println(dizi[i] + " = " + temp);
}
}
}
}
}
You cannot do that from a Map. At least not directly.
Retrieve the keys/entries, get all the map data in a more suitable structure (hint: a class that encapsulates both attributes and is is stored in a sortable (hint2: SortedSet, List)) and sort.
Do not forget to extend Comparable (and implement compareTo) or, otherwise, create a Comparator.
This is one of the solutions take from: https://stackoverflow.com/a/13913206/1256583
Just pass in the unsorted map, and you'll get the sorted one.
private static Map<String, Integer> sortByComparator(Map<String, Integer> unsortMap, final boolean order) {
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
// Sorting the list based on values
Collections.sort(list, new Comparator<Entry<String, Integer>>() {
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
if (order) {
return o1.getValue().compareTo(o2.getValue());
}
else {
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
To print, do a simple iteration over the entry set:
public static void printMap(Map<String, Integer> map) {
for (Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
}
}
You probably have the wrong data structure for this problem. Either:
Reverse the map so the integers are the keys and the words the values and make the map a SortedMap, or
Use a bidirectional map as provided by libraries like Google Guava.
Reversed Map
private final SortedMap<Integer, String> TRANSLATIONS;
static {
SortedMap<Integer, String> map = new TreeMap<>();
map.put(1, "can");
// ...
TRANSLATIONS = Collections.unmodifiableSortedMap(map);
}
Guava BiMap
private final BiMap TRANSLATIONS =
new ImmutableBiMap.Builder<String, Integer>()
.put("ertu", 5);
.put("burak", 4);
.put("selin", 2);
.put("can", 1);
.build();
Then, iterate over a sorted version of the key set or value set as needed. For example,
TRANSLATIONS.inverse.get(4); // "burak"
I'm just curious. What language are your strings in?
all I have list containing Duplicate values I want somehow to get only Unique values from it and store it another list or set.So that I can perform some operation on it.
My code:
{
List<Integer[]> list1 = new ArrayList<Integer[]>();
list1.add(new Integer[] { 1,10 });
list1.add(new Integer[] { 1,10 });
list1.add(new Integer[] { 1,10 });
list1.add(new Integer[] { 2,10 });
list1.add(new Integer[] { 1,10 });
list1.add(new Integer[] { 3,10 });
for(int i=0;i<list1.size();i++)
{
System.out.println("I - 0 :"+list1.get(i)[0]+"\t I - 1 :"+list1.get(i)[1]+"\n");
}
Set<Integer[]> uniquelist = new HashSet<Integer[]>(list1);
for(Integer[] number: uniquelist){
System.out.println(number[0]+"\t"+number[1]);
}
}
I want the result {1,10;2,10;3,10} to be in separate list.When i googled I got to know for unique we should use set as in Set<Integer[]> uniquelist = new HashSet<Integer[]>(list1); But after doing this I dont know how to access each elements Thanks in advance
Output:
1 10
2 10
1 10
3 10
1 10
1 10
You won't get the result you want using the normal Set approach. As your List contains Integer[], and then won't be considered unique by default. All the array objects are distinct. So, your Set will contain the same elements as your list. However, you can define your Custom Comparator, and use it with a TreeSet constructor.
Another way of doing it can be, define a method contains(List<Integer[]> list, Integer[] value), which checks whether your list contains that array. Define a list named uniqueList. Now, iterate over your original list, and then for each value, call contains method passing uniqueList and that value, as parameters.
Here's how your contains method would look like: -
public static boolean contains(List<Integer[]> list, Integer[] value) {
for (Integer[] arr: list) {
// We can compare two arrays using `Arrays.equals` method.
if (Arrays.equals(arr, value)) {
return true;
}
}
return false;
}
So, you can see that, checking for containment is not the same as, how it would look for just Integer.
Now, from your main method, use this code: -
List<Integer[]> unique = new ArrayList<Integer[]>();
for (Integer[] arr: list1) {
// Use your method here, to test whether this value - `arr`
// is already in `unique` List or not. If not, then add it.
if (!contains(unique, arr)) {
unique.add(arr);
}
}
for (Integer[] arr: unique) {
System.out.println(arr);
}
I would rather use a Set implementation in this case. Use LinkedHashSet if you want your elements to be ordered.
You could declare a class IntegerPair to hold your pairs:
class IntegerPair {
private int key;
private int value;
public IntegerPair(int k, int v) {
key = k;
value = v;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
public int hashCode() {
return key * value;
}
public boolean equals(Object o) {
if (!(o instanceof IntegerPair)) {
return false;
}
IntegerPair other = (IntegerPair) o;
return key == other.key && value == other.value;
}
}
Declare it this way:
Set<IntegerPair> set = new LinkedHashSet<IntegerPair>();
Instead of putting new Integer[] values, just do set.add(new IntegerPair(1, 10));
You can loop through your elements using the foreach approach:
for (IntegerPair value : set) {
System.out.println(value.getKey() + " = " + value.getValue());
}
You can access elements by Iterator or by using for each loop
for(Integer number: setOfNumbers){
System.out.println(number);
}
Put them into set using your custom comparator like following:
new TreeSet(list1, new Comparator<Integer[]>() {
public int compare(Integer[] one, Integer[] two) {
int n = one.length;
for (int i = 0; i < n; i++) {
int comp = one.compareTo(two);
if (comp != 0) {
return comp;
}
}
return 0;
}
});
Pay attention that I used TreeSet that can accept custom comparator. It is because you are dealing with arrays. If however you define your own class that holds 2 int values you can make it to implement equals() and hashCode() that allows using any Set implementation.
the Integer[] number in your for loop is an array. to get the values inside you have to use number[index] instruction. to do that you can either do a classic while or for loop using a variable as an index
for(int i=0;i<number.length;i++) {
...
}
or a foreach loop:
for(Integer num : number){
...
}
This may help you...
public static void main(String [] args){
Set<Integer []> set = new TreeSet<Integer []>(new Comparator<Integer[]>(){
public int compare(Integer[] o1, Integer[] o2) {
if(o1.length == o2.length){
for(int i = 0; i < o1.length; i++){
if(o1[i] != o2[i]){
return -1;
}
}
return 0;
}
return -1;
}
});
set.add(new Integer[]{1,2});
set.add(new Integer[]{1,2});
set.add(new Integer[]{1,2});
set.add(new Integer[]{1,3});
int j = 0;
for(Integer[] i: set){
System.out.println("\nElements: "+j);
j++;
for(Integer k : i){
System.out.print(k+" ");
}
}
}
You need to use Comparator to compare two elements of same. As we don't have comparator for Array, Set will use actual object to compare.. using comparator you will have to tell set that this two arrays are same and do not add other same array
Try Table collection in Google-guava.
Example :
Table<Integer, Integer, Integer[]> sampleTable = HashBasedTable.create();
sampleTable.put(1, 10, new Integer[] { 1,10 });
sampleTable.put(2, 10, new Integer[] { 2,10 });
sampleTable.put(1, 10, new Integer[] { 1,10 });
So it will overwrite the duplicate values. Finally you have only unique values.