split the elements in the array list - java

am trying to split elements in array list .
For example i have an arrayList like
List <String> elements = new ArrayList<String>();
elements // ["frnec","fdct","logic","mastro","seloger"]
The size of the elements should be dynamic...
List<List<String>> splittedlists = null;
i want to split the elements like ["frnec"] ,["fdct",logic"],["mastro", "seloger"].
splittedlists //[["frnec"] ,["fdct",logic"],["mastro", "seloger"]].
But the size of the new splittedlists should not exceed 4 ,based on that i have to chop the elements
i had got lots of code code to split lists.But i dont know how to set the maximum size of the 'splittedlists'.
but it will split by setting the target size of spitted elements
public static <T extends Object> List<List<T>> split(List<T> list, int targetSize) {
List<List<T>> lists = new ArrayList<List<T>>();
for (int i = 0; i < list.size(); i += targetSize) {
lists.add(list.subList(i, Math.min(i + targetSize, list.size())));
}
return lists;
}
My requirmeent is to split elements in the list by setting the maximum array size(here 4) of splittedlists
If elements are // ["frnec","fdct"] i want to split is as ["frnec"], ["fdct"]
if elements are // [0, 1, 2, 3, 4, 8, 6] i have to split without exceeding the new array size 4 like
[[0,1],[2,3],[4,8],[6]]

Here is my answer.. Guess you can understand what I'm doing..
List<String> list = new ArrayList<>();
for (int i = 1; i < 11; i++) {
list.add(i+"");
}
List<List<String>> lists = new ArrayList<>();
int x = list.size()/4;
int y = list.size()%4;
int j = 0;
for (int i = 0; i < list.size(); i=j) {
j = i+x;
if(y>0){
j++;
y--;
}
lists.add(list.subList(i, j));
}
System.out.println(list);
System.out.println(lists);

If you don't need to maintain the order you can use modulus (%) operator. So for 3 sublists, it would put the 0th element in the 0th sublist, the first element in the first sublist, the second element in the second sublist, the third element in the 0th sublist, the fourth element in the 1st sublist.... etc.
Something like:
for(int i = 0; i < list.size() ; i++){
listOfLists.get(i % 3).add(list.get(i));
}

Related

Is there a way to iterate through a 2d list where it'll access the elements in order by first index, second, etc

List<List<Integer>> myList = new ArrayList<>(3);
for(int i=0; i < 3; i++) {
myList.add(new ArrayList());
}
myList.get(0).add(1); // 0,0
myList.get(0).add(4); //0,1
myList.get(1).add(2); // 1,0
myList.get(1).add(5); // 1,1
myList.get(2).add(3);// 2,0
myList.get(2).add(6); //2,1
myList.get(2).add(7); //2,3
for(int i =0; i<myList.get(i).size(); i++){
for(int j=0; j<myList.size(); j++){
System.out.println(myList.get(j).get(i));
}
}
I cant figure out how to iterate through the list on a index based, with different lengths on each list. My code above only works if all lists are the same size.
Ideal output would be:
1
2
3
4
5
6
7
But I cant figure out how to print out 7 since that list is a different length. This might be a very simple solution and ill probably feel dumb after. Thanks guys
To iterate over all elements of List of Lists you need to iterate in the first for-loop over the outer List, and in the second for-loop over the inner loop at that index. There are several possibilities to achieve the iteration over all elements, as you will see in the following examples.
(Your code would also produce a IndexOutOfBoundsException for the last entry).
Iterating through a List of Lists
Option 1 (your code corrected)
for (int i = 0; i < myList.size(); i++) { // i represents index of outer List
for (int j = 0; j < myList.get(i).size(); j++) { //j represents index of the inner list at index i
System.out.println(myList.get(i).get(j));
}
}
Option 2 (using for-each loop)
for (List<Integer> innerList : myList) {
for (Integer currentPosition : innerList) {
System.out.println(currentPosition);
}
}
Option 3 (using streams)
myList.stream()
.flatMap(Collection::stream)
.forEach(System.out::println);
}
Edit due to comment: added traverse method for wanted output
If you want to print out all first entries of the inner lists first, a possibility would be to traverse your List<List<Integer>> with a method like this (method is generic, would also work with other classes):
private static <T> List<List<T>> traverse(List<List<T>> input) {
List<List<T>> result = new ArrayList<>();
for (int i = 0; i < input.size(); i++) {
for (int j = 0; j < input.get(i).size(); j++) {
if(result.size() <= j) {
result.add(new ArrayList<>());
}
result.get(j).add(input.get(i).get(j));
}
}
return result;
}
In your method then just create a new List<List<Integer>> like this and iterate over this new list of lists:
List<List<Integer>> myListTraversed = traverse(myList);

ArrayList of ArrayList of Integers should not accept duplicates

The goal is to have no duplicates in my Arraylist of Arraylist of Integers "listResults".
Here I iterate through a list of elements "listOfElements", and if the sum of two elements within this list is equal to the target, then I store indexes of both elements in an ArrayList "pair". Then I add that ArrayList to the list of ArrayList "listResults" and continue iterating.
At the end I might end up with listResults containing one or more arrayLists. However I don't want it to contain duplicates like [2,3] and [3,2] or [4,0] and [0,4]
int target = 60;
ArrayList<ArrayList<Integer>> listResults = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> listOfElements = new ArrayList<Integer>();
listOfElements.add(1);
listOfElements.add(10);
listOfElements.add(25);
listOfElements.add(35);
listOfElements.add(60);
for (int i = 0; i < listOfElements.size(); i++) {
for (int j = 0; j < listOfElements.size(); j++) {
if (listOfElements.get(i) + listOfElements.get(j) == target) {
ArrayList<Integer> pair = new ArrayList<Integer>();
pair.add(i);
pair.add(j);
listResults.add(pair);
}
}
}
System.out.println(listResults);
Based on the current code, the output is: [ [2,3] , [3,2] ] but this is not acceptable as [2,3] and [3,2] are duplicates. Only [2,3] should be allowed as it was the first one to be added to the ArrayList.
You shouldn't check the already visited elements. In your inner for-loop,
change
int j = 0;
to
int j = i + 1;
If the condition is true, use the break statement.

Remove duplicate elements from array along with element in Java 1.7

I need to write a method where a int[] will be supplied as an input and it should return an array, but with all of the numbers that occur more than n times removed entirely.
Inputs:
(int list) data = [1, 2, 2, 3, 3, 3, 4, 5, 5]
Output:
(int list) [1, 4]
These are the steps i have tried.
Copy the int array to ArrayList (inputList).
Create a LinkedHashset to find unique values
Iterate LH and find the collection frequency of ArrayList with iterator.
int[] intArray = new int[0];
if(n!=0){
if(data.length<100){
ArrayList<Integer> inputList = new ArrayList<Integer>(data.length);
//System.out.println(Arrays.toString(data));
for (int i = 0; i < data.length; i++){
inputList.add(Integer.valueOf(data[i]));
}
LinkedHashSet<Integer> lhs = new LinkedHashSet<>(inputList);
intArray = new int[lhs.size()];
int i=0;
int j=0;
Iterator<Integer> itr = lhs.iterator();
while(itr.hasNext()){
Integer shiftNumber = itr.next();
if(Collections.frequency(inputList, shiftNumber)==1) {
intArray[i++] = shiftNumber.intValue();
j++;
}
}
intArray = Arrays.copyOf(intArray, j);
return intArray;
}
}
return intArray;
I am able to achieve the results with the above snippet.However, I need suggestions in reducing the piece of code and improving performance by using any algorithms or other collection objects.
You could use a map instead.
The map key would represent the values found in the array; the map value would be a counter.
You iterate your array, and for each element you either put a counter=1 (when finding that value the first time); or you simply increase that counter.
Finally, you collect only those map keys that show a counter value of 1.
You are likely overcomplicating the algorithm. It might be simpler to just map each value to its frequency and then copy those values with frequency less than n. Also note that you don't need to explicitly covert between int and Integer: Java does it for you automatically.
int[] output = new int[input.length];
Map<Integer,Integer> counts = new HashMap<>();
int size = 0;
for (int i = 0; i < input.length; i++) {
counts.put(input[i], counts.getOrDefault(input[i], 0) + 1);
}
for (int i = 0; i < input.length; i++) {
if (counts.get(input[i]) < n)
output[size++] = input[i];
}
return Arrays.copyOf(output, size);
If you are familiar with Java 8 streams then the code can be substantially reduced:
Map<Integer,Integer> count = Arrays.stream(input).boxed()
.collect(groupingBy(identity(), counting()));
return Arrays.stream(input).filter(i -> count.get(i) < n).toArray();

How to find the Missing Elements in a given sequence array list using java?`

1.I have an Integer array list with a starting element and arraylist limit.
Example [5,6,9,10]
2.In which I have to iterate and find the missing element and its position.
According to the above example ,my output should be number 7 (position3 ),number 8 (position 4) are missing.
3.Now I am getting all the numbers printed instead of getting the missing elements.
Below is the code :
public static List<Integer> issue_ret=new ArrayList<>();
Iterator<Integer> iter = issue_ret.iterator();
while(iter.hasNext()){
int value = iter.next();
if("1".equals(value)){
iter.remove();
}
else{
System.out.println("Missing value:"+value);
}
}
Can anyone help me to resolve this?
Suggest you a more efficient way than ArrayList.contains() but more limited:
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(new Integer[]{5, 6, 9, 10}));
int head = list.get(0);
int tail = list.get(list.size() - 1);
int length = tail - head + 1;
int[] array = new int[length];
for (int i : list) {
array[i - head] = 1;
}
for (int i = 0; i < array.length; i++) {
if (array[i] == 0) {
System.out.println(String.format("Missing %d, position %d", i + head, i + 1));
}
}
The limit is: The top Integer number should not be too large. Anyway, it is a space for time way, whether to use depends on your actual needs.
You are comparing every element with 1
if("1".equals(value))
instead you should keep a counter which will start from your lists first element and then incremented by 1 and perform comparison with this counter.
Try,
List<Integer> integerList = new LinkedList<Integer>();
integerList.add(5);
integerList.add(6);
integerList.add(9);
integerList.add(10);
int first = integerList.get(0);
int last = integerList.get(integerList.size()-1);
for(int i=first+1; i<last; i++){
if(!integerList.contains(i))
System.out.println("Number Not in List : "+i);
}
By getting the first and last element from array you can know the start and end of the array and by iteration over that limit you can get what numbers are missing like below:
List<Integer> input = new ArrayList<Integer>();
input.add(5);
input.add(8);
int firstElement = input.get(0);
int lastElement = input.get(input.size()-1);
for(int i=firstElement+1, j=2; i<lastElement-1; i++,j++){
if(!input.contains(i))
System.out.println("Missing Number : "+i + "(position " + j+")");
}
As we already know that first element and last element is already present in last, no need to check that so we would be only checking of elements exist between first and last element.

max value from arraylist part?

i have some int values stored in ArrayList1 (imagine a table with one column). I need to create another ArrayList2 (second column), which will have values, that are the max values of a range in ArrayList1, for example last 3 values. for example:
1 null
2 null
1 2
3 3
2 3
1 3
So the secondt column - ArrayList2, will contain for each row max value of the last 3 corresponding rows in ArrayList1. (same as in xls, B3=MAX(A1:A3)...).
I can do it by creating for each row with a loop that goes and finds out max value, or i can loop and create subArrayList and use collections.max, but both these solutions require a loop for every row, which isn't very practical, isnt there a simpler way? something like arrayList.max(1,3) to get the number straight away?
You can do something like the code I show below. You iterate the first array, calculating the maximum and updating the second array accordingly. Note that you need an extra array to store the intervals.
private void m1(List<Integer> array1, List<Integer> array2, int range) {
Integer[] rangeArray = new Integer[range];
//Iterate first array
for(int i = 0; i < array1.size(); i++) {
Integer x = array1.get(i);
rangeArray[i%range] = x;
//Update second array
if(i < range - 1) {
array2.add(null);
}
else {
int max = Collections.max(Arrays.asList(rangeArray));
array2.add(max);
}
}
}
Using Collections.max
int startFrom = 2; // configurable number
List<Integer> intList = Arrays.asList(1,2,1,3,2,1,4);
List<Integer> sortedList = new ArrayList<>();
for (int i = 0; i < intList.size(); i++) {
if(i < startFrom){
sortedList.add(null);
continue;
}
ArrayList<Integer> list = new ArrayList<Integer>(intList.subList(i -startFrom, i+1));
sortedList.add(Collections.max(list));
}
System.out.println(sortedList);
Output is :[null, null, 2, 3, 3, 3, 4]
Ok. So your size of list to compare can vary , in that case build an array list out of the numbers to compare say List<?> list = Arrays.asList( numbersToCompare );
then Collections.max( list ), the list should contain objects that can be compared in other words needs to be comparable. ( If not write your own comparator )

Categories