I have two Long array elements and both have some values
Long[] firstArray = new Long[10];
Long[] secondArray = new Long[25];
Both the array may or may not be equal in size.
firstArray[0] = new Long("1");
firstArray[1] = new Long("2");
firstArray[2] = new Long("3");
secondArray [0] = new Long("2");
secondArray [1] = new Long("3");
I want to compare the secondArray with firstArray and create a new thirdArray with the values which are not in secondArray.
In the above example the thirdArray will have only 1
One possible solution would be to convert both of your arrays to List and use removeAll:
Long[] firstArray = new Long[10];
Long[] secondArray = new Long[25];
firstArray[0] = new Long("1");
firstArray[1] = new Long("2");
firstArray[2] = new Long("3");
secondArray [0] = new Long("2");
secondArray [1] = new Long("3");
List<Long> first = new ArrayList<>(Arrays.asList(firstArray));
List<Long> second = Arrays.asList(secondArray);
first.removeAll(second);
Long[] thirdArray = first.toArray(new Long[first.size()]);
It would be more efficient to dump one of the arrays into the set, so you can perform fast search:
Set<Long> set = new HashSet<>(Arrays.asList(second));
After that you can use:
List<Long> list = new ArrayList<>(Arrays.asList(first));
list.removeAll(set);
return list.toArray(new Long[list.size()]);
Or simpler in Java-8:
return Stream.of(first).filter(e -> !set.contains(e)).toArray(Long[]::new);
If you need to keep track of the amounts of repeating elements, you could use a Map<Long, Long>.
Build the map (either a simple for or with stream() and groupingBy()), then iterate over the second array and decrease the count for each key, and then iterate over map's pairs and build the array again.
In Java 8:
Set<Long> set = Stream.of(secondArray).collect(Collectors.toSet());
Long[] thirdArray = Stream.of(firstArray).filter(e -> !set.contains(e)).toArray(Long[]::new);
Related
i need to convert this list: List<double[]> test = new ArrayList<>();
to an 2 dimensional Array with an structure like this :
double[][] test2 = {{3.17, 26.348}, {3.65, 24.198}, {3.28, 25.085}, {3.37, 22.461},
{2.57, 23.740}, {3.60, 24.786}, {3.50, 23.374}, {2.98, 23.725},
{2.54, 23.227}, {3.41, 26.920}..........};
i already tried things like this but it did not work :
List<String[]> list=new ArrayList<String[]>();
double[][] matrix=new double[x34.size()][];
matrix=list.toArray(matrix);
If you are using Java 11 or higher, each collection class has a toArray method which you can use. Example:
List<double[]> myList = List.of(new double[]{3.17, 26.348},
new double[]{3.65, 24.198},
new double[]{3.28, 25.085},
new double[]{3.37, 22.461});
double[][] result = myList.toArray(double[][]::new);
String[][] Array1= {{"A","welcome","S"},
{"B","welcome","S"},
{"C","foodmart","L"},
{"D","welcome","S"},
{"E","publix","M"},};
String[][] Array2= {{"A","welcome","S"},
{"L","welcome","S"},
{"F","foodmart","L"},
{"D","welcome","S"},
{"B","welcome","S"},};
I want to compare the two arrays with 1st value i.e Array1[0][0] with Array2[0][0] and then add the value in the new array if the value is in both arrays if not dont add it in the new array.
Expected Output of the New Array After Comparision.
String[][] Array3 ={{"A","welcome","S"},
{"D","welcome","S"},
{"B","welcome","S"},};
Arrays are not == just because the elements in the arrays are the same. So it is necessary write special compare logic rather than using the collection method retainAll.
Using LinkedHashSet instances for the sets removes duplicates and keeps the set in the same order as the original arrays.
Here are two ways to make this work. I prefer the second way if you are using java 11+.
Using java prior to java 1.8.
Set<String[]> set1 = new LinkedHashSet<>(Arrays.asList(Array1));
Set<String[]> set2 = new LinkedHashSet<>(Arrays.asList(Array2));
Set<String[]> set3 = new LinkedHashSet<String[]>();
Iterator<String[]> it1 = set1.iterator();
while (it1.hasNext()) {
String[] element1 = it1.next();
Iterator<String[]> it2 = set2.iterator();
while (it2.hasNext()) {
String[] element2 = it2.next();
if (element1[0].equals(element2[0])
&& element1[1].equals(element2[1])
&& element1[2].equals(element2[2])) {
set3.add(element1);
}
}
}
set3.toArray(new String[][]{});
And if you are using java 11+ then you can use streams and the var keyword to make things much more readable.
var set1 = new LinkedHashSet<>(Arrays.asList(Array1));
var set2 = new LinkedHashSet<>(Arrays.asList(Array2));
var set3 = new LinkedHashSet<String[]>();
set1.forEach(element1 ->
set2.stream()
.filter(element2 ->
element1[0].equals(element2[0])
&& element1[1].equals(element2[1])
&& element1[2].equals(element2[2]))
.findFirst()
.ifPresent(element2 -> set3.add(element1)));
set3.toArray(new String[][]{});
I have stored these comma separated String in an ArrayList.
[<b>SELL 512<\/b> lots of <b>xyz18#112.00<\/b>, <b>BUY 513<\/b> lots of <b>abc#113.00<\/b>]
I want to remove all the HTML Tags and then further I want to store them in different array List.
Say for eg I want my output something like this.
List3: [SELL, BUY]
List4: [512, 513]
List5: [xyz, abc]
List6: [112, 113]
List<String> List1 = new ArrayList<>();
List<String> List2 = new ArrayList<>();
List<List<String>> Tuples = new ArrayList<List<String>>();
List<String> List3 = new ArrayList<>();
List<String> List4 = new ArrayList<>();
List<String> List5 = new ArrayList<>();
List<String> List6 = new ArrayList<>();
for (int i = 0; i < List1.size(); i++) {
String var = List1.get(i).trim();
for (String x : var.split("\\<.*?\\>|\\#|\\,*$|\\.", 7)) {
List2.add(x);
}
Tuples.add(List2);
}
System.out.println(Tuples);
for (int i = 0; i < Tuples.size(); i++) {
List3.add(Tuples.get(i).get(1).split("\\s")[0].replaceAll("SELL","0").replaceAll("BUY","0"));
List4.add(Tuples.get(i).get(1).split("\\s")[1]);
List5.add(Tuples.get(i).get(3));
List6.add(Tuples.get(i).get(4));
}
System.out.println(List3);
System.out.println(List4);
System.out.println(List5);
System.out.println(List6);
}
But this fetches me output something like this:
List3: [SELL, SELL]
List4: [512, 512]
List5: [xyz, xyz]
List6: [112, 112]
If you inspect the output of System.out.println(Tuples); you'll notice a problem:
Tuples.add(List2) does not make a copy of List2. You're storing multiple references to the same List2 in Tuples, and appending more data to the same List2. So you end up with a very long list (i.e., List2) containing all tuples concatenated, and that list replicated many times inside Tuples.
Instead of
Tuples.add(List2);
try this instead:
Tuples.add(new ArrayList<>(List2));
List2.clear();
This will make elements of Tuples reference different lists.
I think you are doing it in a way too complicated way, just do:
List<String> inputList = new ArrayList<String>();
inputList.add("<b>SELL 512</b> lots of <b>xyz18#112.00</b>");
inputList.add("<b>BUY 513</b> lots of <b>abc#113.00</b>");
System.out.println("inputList: "+inputList);
List<List<String>> Tuples = new ArrayList<List<String>>();
List<String> list3 = new ArrayList<String>();
List<String> list4 = new ArrayList<String>();
List<String> list5 = new ArrayList<String>();
List<String> list6 = new ArrayList<String>();
for (int i = 0; i < inputList.size(); i++) {
String var = inputList.get(i).trim();
String[] splitArr=var.split("</b>|<b>|\\d*#"); //remove the \\d* if you expect to have xyz18 in output instead of x
list3.add((splitArr[1].split("\\s"))[0]);
list4.add((splitArr[1].split("\\s"))[1]);
list5.add(splitArr[3]);
list6.add(splitArr[4]);
Tuples.add(Arrays.asList(var.replaceAll("</b>|<b>", "")));
}
System.out.println("Tuples: "+Tuples);
System.out.println("list3: "+list3);
System.out.println("list4: "+list4);
System.out.println("list5: "+list5);
System.out.println("list6: "+list6);
OUTPUT:
inputList: [<b>SELL 512</b> lots of <b>xyz18#112.00</b>, <b>BUY 513</b> lots of <b>abc#113.00</b>]
Tuples: [[SELL 512 lots of xyz18#112.00], [BUY 513 lots of abc#113.00]]
list3: [SELL, BUY]
list4: [512, 513]
list5: [xyz, abc]
list6: [112.00, 113.00]
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));
I have an ArrayList named play_viewCount: I am sorting this ArrryList and storing it in a new ArrayList.
Now I have sorted ArrayList: but what I want is before sorting what was the position of new items in ArrayList?
ArrayList<String> sort_play_viewCount = play_ViewCount; // here play_viewCount is ArrayList
ArrayList<Integer> position_array = new ArrayList<Integer>();
System.out.println("......................................... Play Count :"+sort_play_viewCount);
Collections.sort(sort_play_viewCount);
System.out.println(".........................................sort Play Count :"+sort_play_viewCount);
for(int j = 0; j<sort_play_viewCount.size(); j++){
for(int k = 0; k<sort_play_viewCount.size(); k++){
if(play_ViewCount.contains(sort_play_viewCount.get(j))){
position_array.add(k);
}
}
}
System.out.println(" .................Position Array: "+position_array);
Does anyone know how to get the positions of the new items before sorting?
Try doing a little differently:
ArrayList<Integer> position_array = new ArrayList<Integer>();
position_array.addAll(play_viewCount);
Collections.sort(position_array);
Now position_array is sorted, and to get the previous positions you can just call play_viewCount.indexOf(value);
You can put the elements of the ArrayList into a Map<String, Integer> (implemented by a HashMap<String, Integer>), where the key of an entry is String element from the ArrayList and the value is Integer representing the position.
Map<String, Integer> originalPositions = new HashMap<String, Integer>();
String item = ...
String position = ...
originalPositions.put(item, position);
// do something with the ArrayList, such as sorting
Collections.sort(arrayList);
String someItem = arrayList.get(i);
int originalPosition = originalPositions.get(someItem);
And by the way, this line from your code snippet doesn't do what you think it does:
ArrayList<String> sort_play_viewCount = play_ViewCount;
It doesn't create a new ArrayList with the same contents as the original one. Instead, it just creates a new reference to the original ArrayList. Both play_ViewCount and sort_play_viewCount refer to the very same object, in other words, any changes to one of the variables (such as sorting) also affect the other one.
To create a new copy (however, it is still shallow) of an ArrayList, use the following idiom:
ArrayList<Integer> original = ...
ArrayList<Integer> copy = new ArrayList<Integer>(original);