Use the Stream API in Java 8

 

  1. Convert a List of Strings to uppercase:
java
List<String> strings = Arrays.asList("apple", "banana", "cherry"); 
List<String> uppercaseStrings = strings.stream() .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(uppercaseStrings); // [APPLE, BANANA, CHERRY]
  1. Filter a List of integers to only include even numbers:
java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); System.out.println(evenNumbers); // [2, 4, 6, 8, 10]
  1. Calculate the sum of a List of integers:
java
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); int sum = numbers.stream() .reduce(0, Integer::sum); System.out.println(sum); // 55
  1. Group a List of objects by a property:
java
List<Person> people = Arrays.asList( new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 35), new Person("Alice", 40) ); Map<String, List<Person>> peopleByFirstName = people.stream() .collect(Collectors.groupingBy(Person::getFirstName)); System.out.println(peopleByFirstName); // {Alice=[Person(firstName=Alice, age=25), Person(firstName=Alice, age=40)], // Bob=[Person(firstName=Bob, age=30)], // Charlie=[Person(firstName=Charlie, age=35)]}
  1. Sort a List of strings alphabetically:
java
List<String> strings = Arrays.asList("banana", "apple", "cherry"); List<String> sortedStrings = strings.stream() .sorted() .collect(Collectors.toList()); System.out.println(sortedStrings); // [apple, banana, cherry]
  1. Find the maximum value in a List of integers:
java
List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3); Optional<Integer> max = numbers.stream() .max(Integer::compare); System.out.println(max); // Optional[9]
  1. Find the first element of a List of strings that starts with a given letter:
java
List<String> strings = Arrays.asList("apple", "banana", "cherry", "apricot", "blueberry"); Optional<String> first = strings.stream() .filter(s -> s.startsWith("a")) .findFirst(); System.out.println(first); // Optional[apple]
  1. Map a List of objects to a List of their properties:
java
List<Person> people = Arrays.asList( new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 35) ); List<String> firstNames = people.stream() .map(Person::getFirstName) .collect(Collectors.toList()); System.out.println(firstNames); // [Alice, Bob, Charlie]

Create optional get Item list



This code uses findFirst() to find the first SectionOffer that matches the selected discipline, and then uses map() to get its id. If no matching SectionOffer is found, the code sets a default value of -1 (you can change this to whatever makes sense for your use case). Finally, the id is displayed in a toast message.

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
secID = sectionOffers.stream()
.filter(s -> s.getDiscipline().contains(binding.spinnerDiscipline.getSelectedItem().toString()))
.findFirst()
.map(SectionOffer::getId)
.orElse(-1);
}

String store array list

String allCourses=null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
// change arrayList to string
allCourses =selectCourseObj.stream()
.map(s->String.valueOf(s.getId()))
.collect(Collectors.joining(", "));

String array list

ArrayList<Integer> selectCourse= new ArrayList<>();
String allCourses = String.join(", ",String.valueOf(selectCourse));


Here, the map() method is used to extract the discipline property from each SectionOffer object in the list and return a stream of String objects. The collect() method is then used to collect this stream into a new ArrayList of String objects..

ArrayList<String> courseNames = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
courseNames = sectionOffers.stream()
.map(SectionOffer::getDiscipline)
.collect(Collectors.toCollection(ArrayList::new));
}
    1. ArrayList<Map<String, String>> maplist: Declares an ArrayList to hold a collection of maps. Each map represents a JSON object with key-value pairs.

    2. String datajson: Represents the JSON string containing the data to be parsed and displayed in the Spinner.

    3. maplist = new Gson().fromJson(datajson, new TypeToken<ArrayList<Map<String, String>>>(){}.getType()): Utilizes Gson to parse the JSON string into an ArrayList of maps. The TypeToken class is used to specify the desired type of the resulting object.

    4. if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N): Checks if the device's Android version is compatible with Java 8 features.

    5. ArrayList<String> dataList = maplist.stream().map(map -> map.get("discipline")).collect(Collectors.toCollection(ArrayList::new)): Applies Java 8 streams to the maplist to extract the value associated with the key "discipline" from each map. The resulting values are collected into a new ArrayList called dataList.

    6. ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList): Creates an ArrayAdapter with the dataList as the data source. It uses the system-provided layout android.R.layout.simple_list_item_1 for each item in the Spinner.

    7. binding.spinnerTeacherDiscipline.setAdapter(adapter): Sets the created adapter to the Spinner, populating it with the extracted values.

    By parsing the JSON string, extracting the desired values using Java 8 streams, and setting them as the data source for the ArrayAdapter, you can populate a Spinner with the extracted values from the JSON data.

    ArrayList<Map<String,String>> maplist;
    String datajson= "[\n" +
    " {\n" +
    " \"id\": 65,\n" +
    " \"discipline\": \"BCS-2C\"\n" +
    " }, {\n" +
    " \"id\": 88,\n" +
    " \"discipline\": \"BCS-2C\"\n" +
    " }\n" +
    "]";

    maplist= new Gson().fromJson(datajson, new TypeToken<ArrayList<Map<String,String>>>(){}.getType());
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    ArrayList<String> dataList = maplist.stream()
    .map(map -> map.get("discipline")) // Replace "key" with the actual key you want to extract from the map
    .collect(Collectors.toCollection(ArrayList::new));
    ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
    android.R.layout.simple_list_item_1, dataList);
    binding.spinnerTeacherDiscipline.setAdapter(adapter);

    }
  1. Combine two Lists of integers by adding their corresponding elements:
java
List<Integer> list1 = Arrays.asList(1, 2, 3

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.