Skip to content

Instantly share code, notes, and snippets.

@thanoojgithub
Last active February 24, 2021 16:19
Show Gist options
  • Save thanoojgithub/6940fc119f7e8675fa313389e48d0e97 to your computer and use it in GitHub Desktop.
Save thanoojgithub/6940fc119f7e8675fa313389e48d0e97 to your computer and use it in GitHub Desktop.
Java By Examples
1. How to find out second hightest value from a Map<String, Integer>
Map<String, Integer> books = new HashMap<>();
books.put("one", 1);
books.put("two", 22);
books.put("three", 333);
books.put("four", 4444);
books.put("five", 55555);
books.put("six", 666666);
Stream<Integer> list = books.entrySet().stream().filter(e -> e.getValue().toString().length() > 3)
.map(Map.Entry::getValue);
List<Integer> valuesList = list.collect(Collectors.toList());
valuesList.sort(Comparator.naturalOrder());
Object o = valuesList.toArray()[1];
System.out.println(o);
2. Find whether given string is valid or not.
String str = "{{{{}}}}";
int openB = 0;
char[] charArray = str.toCharArray();
for (char chr : charArray) {
if (chr == '{') {
openB += 1;
} else {
openB -= 1;
}
}
if (openB == 0) {
System.out.println("valid");
} else {
System.out.println("in-valid");
}
3. Find 2nd Hightest number from a given int array
int arr[] = {12, 35, 1, 10, 34, 1};
int i, first, second;
first = second = Integer.MIN_VALUE;
for (i = 0; i < arr.length; i++) {
/* If current element is smaller than
first then update both first and second */
if (arr[i] > first) {
second = first;
first = arr[i];
} else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
System.out.println(second);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment