In this post I will keep some useful Java hacks and one-liners which are useful in every day programming
Multiple Each Item in a List by 2
IntStream.range(1, 10).map(i -> i * 2);
Sum a List of Numbers
IntStream.range(1, 100).sum();
Verify if String exists in a List
List wordList = Arrays.asList("Maven", "jdk", "JBoss", "java"); String tweet = "This is a JBoss tutorial"; wordList.stream().anyMatch(str::contains);
Create a Map where keys are “true” if > 50
Map<Boolean, List<Integer>> passedFailedMap = Stream.of(29, 18, 76, 82, 50, 88).collect(Collectors.partitioningBy(i -> i > 50)); System.out.println(passedFailedMap); //{false=[29, 18, 50], true=[76, 82, 88]}
Find minimum (or maximum) in a List:
IntStream.of(24, 45, -3, 26, 18).min(); Arrays.asList(24, 45, -3, 26, 18).stream().min(Integer::compare); Arrays.asList(24, 45, -3, 26, 18).stream().reduce(Integer::min); Collections.min(Arrays.asList(24, 45, -3, 26, 18));
Sorted List by HashMap keys:
SortedSet keys = new TreeSet(myHashMap.keySet());
Sorted List by HashMap values:
SortedSet values = new TreeSet(myHashMap.values());
Sort a Map by values
Stream<Map.Entry<K,V>> sorted = map.entrySet().stream() .sorted(Map.Entry.comparingByValue());
Sorting ArrayList in ascending Order
Collections.sort(list);
Sort an ArrayList using a custom Object’s property
Collections.sort(Database.arrayList, (o1, o2) -> o1.getStartDate().compareTo(o2.getStartDate()));
How to generate a Random String
String uuid = UUID.randomUUID().toString();
Parallel Processing
List dataList = null; dataList.parallelStream().map(line -> processItem(line));
Read a File in one line
String fileText = new String(Files.readAllBytes(Paths.get("data.txt"))); List fileLines = Files.readAllLines(Paths.get("data.txt"));
Initialization of an ArrayList in one line
List<String> places = Arrays.asList("Cat", "Dog", "Mouse");
How do I determine whether an array contains a particular value in Java?
Arrays.asList(yourArray).contains(yourValue) String[] values = {"AB","BC","CD","AE"}; boolean contains = Arrays.stream(values).anyMatch("s"::equals);
How to print the content of an Array
String[] array = new String[] {"Fred", "John", "Bob"}; System.out.println(Arrays.toString(array));
Create ArrayList from array
new ArrayList<>(Arrays.asList(array));
How do I read / convert an InputStream into a String in Java?
#Option 1 String result = org.apache.commons.io.IOUtils.toString(inputStream, StandardCharsets.UTF_8); #Option 2 Scanner s = new Scanner(inputStream).useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; #Option 3 ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; for (int length; (length = inputStream.read(buffer)) != -1; ) { result.write(buffer, 0, length); } return result.toString("UTF-8");
How do I iterate over each entry in a Java Map?
Map<String, String> map = ... for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); } #Java 10+: for (var entry : map.entrySet()) { System.out.println(entry.getKey() + "/" + entry.getValue()); }
Java CheatSheet – by Mastertheboss (2022). Read more CheatSheets.