/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package javaapplication6; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; /** * * @author ZZaier */ public class JavaApplication6 { /** * @param args the command line arguments */ public static void main(String[] args) { List myList1 = new ArrayList(Arrays.asList(3, 15, 5, 78, 4, -111, 55, 5, 33)); System.out.println("Sum is " + sumValue(myList1)); System.out.println("max is " + maxValue(myList1)); System.out.println("position even is " + evenValue(myList1)); System.out.println("negative is " + negativeValues(myList1)); System.out.println("first is " + searchLastValue(myList1, 5)); System.out.println("last is " + searchFirstValue(myList1, 5)); System.out.println("old list is " + myList1); System.out.println("new list is " + insertValueInList(myList1, 25, 5)); List myList2 = new ArrayList(Arrays.asList(3, 15, 15, 78, 114, 114, 114, 155, 225, 733, 733, 733)); searchDoubleValue(myList2); } public static int sumValue(List list) { //we don't initialize at 0 int sum = 0; for (int value : list) { sum += value; } return sum; } public static int maxValue(List list) { int max = list.get(0); for (int i = 0; i < list.size(); i++) { if (max < list.get(i)) { max = list.get(i); } } return max; } public static int negativeValues(List list) { int count = 0; for (int i = 0; i < list.size(); i++) { if (list.get(i) < 0) { count++; } } return count; } public static int evenValue(List list) { int position = -1; for (int i = 0; i < list.size(); i++) { if (list.get(i) % 2 == 0) { position = i; } } return position; } public static int searchLastValue(List list, int value) { int position = -1; for (int i = 0; i < list.size(); i++) { if (list.get(i) == value) { position = i; } } return position; } public static int searchFirstValue(List list, int value) { int i = 0; while (i < list.size() && list.get(i) != value) { i++; } if (i < list.size()) { return i; } else { return -1; } } public static void searchDoubleValue(List list) { for (int i = 0; i < list.size() - 1; i++) { if (Objects.equals(list.get(i), list.get(i + 1))) { System.out.println(list.get(i)); } } } public static List insertValueInList(List list, int value, int position) { // we don't want to use the add list function int theSize = list.size(); if(position> theSize) { System.out.println("Position Out of bound"); return list; } list.add(99); for (int i = theSize; i > position; i--) { list.set(i,list.get(i-1) ); } list.set(position,value ); return list; } }