Remove duplicates form arraystring - java

I have filled in an ArrayList of strings with suppliernumbers. This list contains duplicates values so I want to delete them with the HashSet.
I get following error: Invalid expression as statement
On line => Set set = new HashSet(leveranciers); (Set underlined)
Any idea why?
String[] leveranciers = new String[wdContext.nodeShoppingCart().size()];
for(int i = 0; i<wdContext.nodeShoppingCart().size(); i++){
String productnumber = wdContext.nodeShoppingCart().getShoppingCartElementAt(i).getMatnr()
wdThis.wdGetAchatsIndirectController().GetDetails(productnumber, "NL");
leveranciers[i] = wdContext.currentEt_DetailsElement().getLifnr();
}
//Remove duplicates from array
Set<String> set = new HashSet<String>(leveranciers);
set.toArray(new String[0]);
for(int y = 0; y<set.size();y++){
PdfPTable table = GetTable(set[y]);
byte[] pdf = wdThis.wdGetAchatsIndirectController().GetPDFFromFolder("/intranetdocuments/docs/AchatsIndirect", table);
wdThis.wdGetAchatsIndirectController().PrintPDF(pdf);
}

HashSet doesn't have a constructor which accepts an array.
Have a look at HashSet documentation.
http://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
You can achieve your goal by using Arrays.asList method like that:
final String[] strings = new String[] {"ab", "ba", "ab"};
final Set<String> set = new HashSet<String>(Arrays.asList(strings));

Related

Find unique value of string array and keep order

I have a String[] with values like so:
line_str = "1,3,4,3,11,2,2,6,7"
I want to find unique value and keep the arrangement of value
unique_str="1,3,4,11,2,6,7"
I'm using a HashSet but the output is:
[1,6,7,4,11,3,2]
Here is my code:
String line_str = "1,3,4,3,11,2,2,6,7";
String[] str_arr = line_str.split(",");
Set<String> uniqueValue = new HashSet<>(Arrays.asList(str_arr));
Toast.makeText(this, uniqueValue.toString(),Toast.LENGTH_LONG).show();
A HashSet will ensure no duplications and a LinkedHashSet will ensure each element remains in its designated position;
String line_str = "1,3,4,3,11,2,2,6,7";
String[] str_arr = line_str.split(",");
Set<Integer> uniqueNumbers = new LinkedHashSet<Integer>();
for(String num : str_arr) {
uniqueNumbers.add(Integer.parseInt(num));
}
If your input has any variance then you will need to handle that.
Using streams :
String line_str = "1,3,4,3,11,2,2,6,7";
String unique_str = Pattern.compile(",")
.splitAsStream(line_str)
.distinct()
.collect(Collectors.joining(","));
System.out.println(unique_str);

Java: Removing item from array because of character

Lets say you have an array like this: String[] theWords = {"hello", "good bye", "tomorrow"}. I want to remove/ignore all the strings in the array that have the letter 'e'. How would I go about doing that? My thinking is to go:
for (int arrPos = 0; arrPos < theWords.length; arrPos++) { //Go through the array
for (int charPos = 0; charPos < theWords[arrPos].length(); charPos++) { //Go through the strings in the array
if (!((theWords[arrPos].charAt(charPos) == 'e')) { //Finds 'e' in the strings
//Put the words that don't have any 'e' into a new array;
//This is where I'm stuck
}
}
}
I'm not sure if my logic works and if I'm even on the right track. Any responses would be helpful. Many thanks.
One easy way to filter an array is to populate an ArrayList with if in a for-each loop:
List<String> noEs = new ArrayList<>();
for (String word : theWords) {
if (!word.contains("e")) {
noEs.add(word);
}
}
Another way in Java 8 is to use Collection#removeIf:
List<String> noEs = new ArrayList<>(Arrays.asList(theWords));
noEs.removeIf(word -> word.contains("e"));
Or use Stream#filter:
String[] noEs = Arrays.stream(theWords)
.filter(word -> !word.contains("e"))
.toArray(String[]::new);
You can directly use contains() method of String class to check if "e" is present in your string. That will save your extra for loop.
It would be simple if you use ArrayList.
importing import java.util.ArrayList;
ArrayList<String> theWords = new ArrayList<String>();
ArrayList<String> yourNewArray = new ArrayList<String>;//Initializing you new array
theWords.add("hello");
theWords.add("good bye");
theWords.add("tommorow");
for (int arrPos = 0; arrPos < theWords.size(); arrPos++) { //Go through the array
if(!theWords.get(arrPos).contains("e")){
yourNewArray.add(theWords.get(arrPos));// Adding non-e containing string into your new array
}
}
The problem you have is that you need to declare and instantiate the String array before you even know how many elements are going to be in it (since you wouldn't know how many strings would not contain 'e' before going through the loop).
Instead, if you use an ArrayList you do not need to know the required size beforehand. Here is my code from start to end.
String[] theWords = { "hello", "good bye", "tomorrow" };
//creating a new ArrayList object
ArrayList<String> myList = new ArrayList<String>();
//adding the corresponding array contents to the list.
//myList and theWords point to different locations in the memory.
for(String str : theWords) {
myList.add(str);
}
//create a new list containing the items you want to remove
ArrayList<String> removeFromList = new ArrayList<>();
for(String str : myList) {
if(str.contains("e")) {
removeFromList.add(str);
}
}
//now remove those items from the list
myList.removeAll(removeFromList);
//create a new Array based on the size of the list when the strings containing e is removed
//theWords now refers to this new Array.
theWords = new String[myList.size()];
//convert the list to the array
myList.toArray(theWords);
//now theWords array contains only the string(s) not containing 'e'
System.out.println(Arrays.toString(theWords));

How to get value from List<String[]>

I'm successfully getting the values from CSV file in to List<String[]>, but having problem in moving values from List<String[]> to String[] or to get single value from List. I want to copy these values in to string array to perform some functions on it.
My values are in scoreList
final List<String[]> scoreList = csvFile.read();
Now I want to get single value from this scoreList. I have tried this approaches but could not get the value
String[] value=scoreList.get(1);
You want a single value but you are declearing an array an you are tring to assign string to string array. If you want a single value, try this;
String x = scoreList.get(1);
or
if you want to convert listarray to string array try this;
String[] myArray = new String[scoreList.size()];
for(int i=0; i<scoreList.size();i++)
{
myArray[i]=scoreList.get(i);
}
Suppose you want to collect values of the 2nd column (index 1) then you can try this
// Collect values to this list.
List<String> scores = new ArrayList<String>();
final List<String[]> scoreList = csvFile.read();
// For each row in the csv file
for (String [] scoreRow : scoreList ) {
// var added here for readability. Get second column value
String value = scoreRow[1];
scores.add(value);
}

Error on Convert ArrayList to Arrays PayPalItem

I need a Array to PayPal Items must however go another arraylist to add the items as I do that?
ArrayList<PayPalItem[]> stringArrayList = new ArrayList<PayPalItem[]>();
for (int i=0; i<resultado.size(); i++) {
PayPalItem[] items;
double x = Math.round(((resultado.get(i).getTotal() / resultado.get(i).getPreco())));
int quantidade = (int) x;
String preco = String.format("%.2f", resultado.get(i).getPreco());
String nome = resultado.get(i).getProduto();
items = new PayPalItem[]{
new PayPalItem(nome, quantidade, new BigDecimal(resultado.get(i).getPreco()), "BRL",
"dinner")
};
stringArrayList.add(items); //add to arraylist
}
PayPalItem[] items = new PayPalItem[stringArrayList.size()];
//if you want your array
PayPalItem[] stringArray = stringArrayList.toArray(items);
I'm trying to convert an ArrayList to the Array however I get this error
Conversion from an arrayList i.e. ArrayList<Something> list to an Array is done this way (as you already did):
list.toArray(Something[]) <- notice that the parameter here is an array of Something elements.
so in your case: Something is PayPalItem[] then you need to add an extra [] because you have an array of arrays.
replacing your last two lines of your code by these two will solve your issue.
PayPalItem[][] items = new PayPalItem[stringArrayList.size()][];
//if you want your array
PayPalItem[][] stringArray = stringArrayList.toArray(items);
but anyway, I cannot understand why do you need an array of arrays instead of simply just a list or an array. I mean something like this:
ArrayList<PayPalItem> stringArrayList = new ArrayList<PayPalItem>();
for (int i = 0; i < 2; i++) {
//create the PayPalItem and add to the list
stringArrayList.add(new PayPalItem()); //add to arraylist
}
PayPalItem[] items = new PayPalItem[stringArrayList.size()];
//if you want your array
PayPalItem[] stringArray = stringArrayList.toArray(items);

How to convert ArrayList to String[] in java, Arraylist contains VO objects

Please help me to convert ArrayList to String[]. The ArrayList contains values of type Object(VO).
For example,
The problem is that I need to convert a country List to String Array, sort it and then put it in a list. However I am getting a ClassCastException.
String [] countriesArray = countryList.toArray(new String[countryList.size()]);
I have assumed that your country List name is countryList.
So to convert ArrayList of any class into array use following code. Convert T into the class whose arrays you want to create.
List<T> list = new ArrayList<T>();
T [] countries = list.toArray(new T[list.size()]);
Please help me to convert ArrayList to String[], ArrayList Contains
Values Object(VO) as Values.
As you mentioned that list contains Values Object i.e. your own class you need toString() overridden to make this work correctly.
This code works. Assuming VO is your Value Object class.
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] result = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
result[i] = listOfValueObject.get(i).toString();
}
Arrays.sort(result);
List<String> sortedList = Arrays.asList(result);
The snippet of
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] countriesArray = listOfValueObject.toArray(new String[listOfValueObject.size()]);
will give you ArrayStoreException due VO is not the String type as required by native method arraycopy subsequently called from toArray one.
In case your ArrayList contains Strings, you can simply use the toArray method:
String[] array = list.toArray( new String[list.size()] );
If that is not the case (as your question is not completely clear on this), you will have to manually loop over all elements
List<MyRandomObject> list;
String[] array = new String[list.size() ];
for( int i = 0; i < list.size(); i++ ){
MyRandomObject listElement = list.get(i);
array[i] = convertObjectToString( listElement );
}
String[] array = list.toArray(new String[list.size()]);
What are we doing here:
String[] array is the String array you need to convert your
ArrayList to
list is your ArrayList of VO objects that you have in hand
List#toArray(String[] object) is the method to convert List objects
to Array objects
As correctly suggested by Viktor, I have edited my snippet.
The is a method in ArrayList(toArray) like:
List<VO> listOfValueObject // is your value object
String[] countries = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
countries[i] = listOfValueObject.get(i).toString();
}
Then to sort you have::
Arrays.sort(countries);
Then re-converting to List like ::
List<String> countryList = Arrays.asList(countries);
Prior to Java 8 we have the option of iterating the list and populating the array, but with Java 8 we have the option of using stream as well. Check the following code:
//Populate few country objects where Country class stores name of country in field name.
List<Country> countries = new ArrayList<>();
countries.add(new Country("India"));
countries.add(new Country("USA"));
countries.add(new Country("Japan"));
// Iterate over list
String[] countryArray = new String[countries.size()];
int index = 0;
for (Country country : countries) {
countryArray[index] = country.getName();
index++;
}
// Java 8 has option of streams to get same size array
String[] stringArrayUsingStream = countries.stream().map(c->c.getName()).toArray(String[]::new);

Categories