-7

Given a list of integers 1,2,3,etc. remove all values greater than 100? What will be the JAVA code for this?

import java.util.ArrayList;
import java.util.List;

public class Main {

public static void main(String[] args) {
    int[] given_list = {0,4,5,56,3, 2000, 453,};


    }
}
2
  • 4
    This is not a site for people to do your homework for you. You have to attempt to write the code yourself first, and when you have issues with it you post your code (after you do research first) that is not working and we tell you what is wrong with it.
    – Nexevis
    Oct 3, 2019 at 15:33
  • 2
    Arrays.stream(given_list).filter(i -> i <= 100).toArray() Oct 3, 2019 at 16:23

3 Answers 3

0

Using Java 8 Stream API this can be achieved in a single line code:

Arrays.stream(given_list).filter(x -> x<100).toArray()

Above line of code creates a new array and does not modify the original array.

0

I show you the easiest way...

List<Integer> given_list  = new ArrayList<>(Arrays.asList(new Integer[] {0,4,5,56,3, 2000, 453}));
given_list.removeIf(element -> element > 100);
System.out.println(given_list);
-1
import java.util.ArrayList;
import java.util.List;

public class DeleteFromList {

public static void main(String[] args) {
   int[] given_list = {0,4,5,56,3, 2000,8,345, 453,}; 

   //since there is no direct way to delete an element from the array we have to use something other than array, like a list.
   List<Integer> list = new ArrayList<Integer>();

   //this changes the whole array to list
   for (int i : given_list){
      list.add(i);
   }

   //this iterates through the list and check each element if its greater then 100
   for(int i=0;i<list.size();i++){
      if(list.get(i) > 100){
         list.remove(i);
         i--;     // this is because everytime we delete an element, the next comes in place of it so we need to check new element.
      }
   }

   //print out the new list which has all the elements which are less than 100
   System.out.println(list);

   }
}

Since there is no way to delete an element from an array, we have to change array to list and then operate on that list so we can delete elements as we want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.